const express = require('express');
const db = require('../config/database');
const crypto = require('crypto');
const { activateSubscription } = require('../services/subscriptionService');
const router = express.Router();

// Razorpay Webhook Handler
router.post('/razorpay/webhook', async (req, res) => {
  try {
    const webhookSecret = process.env.RAZORPAY_WEBHOOK_SECRET;
    const signature = req.headers['x-razorpay-signature'];

    // Verify webhook signature
    const expectedSignature = crypto
      .createHmac('sha256', webhookSecret)
      .update(JSON.stringify(req.body))
      .digest('hex');

    if (signature !== expectedSignature) {
      console.error('Invalid webhook signature');
      return res.status(400).json({ message: 'Invalid signature' });
    }

    const event = req.body.event;
    const payload = req.body.payload;

    console.log(`Webhook received: ${event}`);

    switch (event) {
      case 'payment.authorized':
      case 'payment.captured':
        await handlePaymentSuccess(payload.payment.entity);
        break;

      case 'payment.failed':
        await handlePaymentFailure(payload.payment.entity);
        break;

      case 'order.paid':
        await handleOrderPaid(payload.order.entity);
        break;

      default:
        console.log(`Unhandled webhook event: ${event}`);
    }

    res.json({ status: 'ok' });
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(500).json({ message: 'Webhook processing failed' });
  }
});

async function handlePaymentSuccess(payment) {
  try {
    const razorpayOrderId = payment.order_id;
    const razorpayPaymentId = payment.id;

    // Find transaction by order ID
    const [transactions] = await db.execute(
      `SELECT pt.*, JSON_EXTRACT(pt.metadata, '$.subscription_id') as subscription_id
       FROM payment_transactions pt
       WHERE pt.gateway_transaction_id = ? AND pt.status = 'pending'`,
      [razorpayOrderId]
    );

    if (transactions.length === 0) {
      console.log(`No pending transaction found for order: ${razorpayOrderId}`);
      return;
    }

    const transaction = transactions[0];
    const subscriptionId = transaction.subscription_id;

    // Update transaction status
    await db.execute(
      `UPDATE payment_transactions
       SET status = 'completed', 
           gateway_transaction_id = ?, 
           gateway_response = ?,
           processed_at = NOW()
       WHERE transaction_id = ?`,
      [razorpayPaymentId, JSON.stringify(payment), transaction.transaction_id]
    );

    // Activate subscription if exists
    if (subscriptionId) {
      await activateSubscription(subscriptionId, transaction.user_id);
      console.log(`Subscription ${subscriptionId} activated via webhook`);
    }

    // Update invoice if exists
    if (transaction.invoice_id) {
      await db.execute(
        'UPDATE invoices SET status = "paid" WHERE id = ?',
        [transaction.invoice_id]
      );
    }

    console.log(`Payment ${razorpayPaymentId} processed successfully via webhook`);
  } catch (error) {
    console.error('Error handling payment success:', error);
    throw error;
  }
}

async function handlePaymentFailure(payment) {
  try {
    const razorpayOrderId = payment.order_id;

    // Update transaction status to failed
    await db.execute(
      `UPDATE payment_transactions
       SET status = 'failed',
           gateway_response = ?,
           processed_at = NOW()
       WHERE gateway_transaction_id = ?`,
      [JSON.stringify(payment), razorpayOrderId]
    );

    console.log(`Payment failed for order: ${razorpayOrderId}`);
  } catch (error) {
    console.error('Error handling payment failure:', error);
    throw error;
  }
}

async function handleOrderPaid(order) {
  try {
    console.log(`Order paid: ${order.id}`);
    // Additional order-level processing if needed
  } catch (error) {
    console.error('Error handling order paid:', error);
    throw error;
  }
}

module.exports = router;
