import type { Context } from "koa";
import { ObjectId } from "mongodb";
import dbConfig from "../config/database";
import DatabaseService from "../services/database";
import webpush from "web-push";

// Configure web-push with VAPID keys
const vapidKeys = {
  // These should be replaced with generated keys from the script
  publicKey: process.env.VAPID_PUBLIC_KEY || 'BEHsROsRzfqdMv4g50BEKUbFEL0NNdig0yxdmd-d9j5ZNLOOWbwsTZY3q_W_Y2E-h-hCCJmC5r3uATdFKQTN4z0',
  privateKey: process.env.VAPID_PRIVATE_KEY || 'dhty4Wi3rKZlKRs_7zSPmcW6qEK8sCMZ23Qw9iMGuBM'
};

webpush.setVapidDetails(
  'mailto:support@budgetmanager.com',
  vapidKeys.publicKey,
  vapidKeys.privateKey
);

const db = DatabaseService.getInstance();

export default {
  // Get VAPID public key
  async getVapidPublicKey(ctx: Context) {
    ctx.set('Content-Type', 'text/plain');
    ctx.body = vapidKeys.publicKey;
    console.log("Returning VAPID public key:", vapidKeys.publicKey);
  },
  
  // Register a new push subscription
  async registerPushSubscription(ctx: Context) {
    const user = (ctx.state as any).user;
    const userId = user.id;
    const { subscription } = ctx.request.body;
    
    if (!subscription) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "Subscription data is required"
      };
      return;
    }
    
    try {
      const subscriptionsCollection = db.getCollection(
        dbConfig.collections.pushSubscriptions
      );
      
      // Store subscription with user ID
      await subscriptionsCollection.updateOne(
        { userId: new ObjectId(String(userId)) },
        { $set: { subscription, updatedAt: new Date() } },
        { upsert: true }
      );
      
      ctx.body = {
        success: true,
        message: "Push subscription registered successfully"
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: "Error registering push subscription",
        error: (error as Error).message
      };
    }
  },
  
  // Send notification for a new transaction
  async sendTransactionNotification(userId: string, transaction: any) {
    try {
      const subscriptionsCollection = db.getCollection(
        dbConfig.collections.pushSubscriptions
      );
      
      // Find user's subscription
      const record = await subscriptionsCollection.findOne({
        userId: new ObjectId(String(userId))
      });
      
      if (!record || !record.subscription) {
        return { success: false, message: "No subscription found" };
      }
      
      // Prepare notification payload
      const payload = JSON.stringify({
        message: `New ${transaction.type}: ${transaction.description || 'Transaction'} - ${transaction.amount}`,
        additionalData: {
          transactionId: transaction._id.toString(),
          type: transaction.type
        }
      });
      
      // Send push notification
      await webpush.sendNotification(record.subscription, payload);
      
      return { success: true };
    } catch (error) {
      console.error("Error sending push notification:", error);
      return { success: false, error: (error as Error).message };
    }
  }
};
