import { Router, Request, Response } from 'express';
import { db } from '../../database/db';
import { PaymentGatewayService } from './payment.service';
import { BillingService } from '../billing/billing.service';

const router = Router();

// ==========================================
// 1. OFFICIAL bKASH PAY BILL ENDPOINTS
// ==========================================

// GET & POST /api/bkash/validate - bKash customer inquiry validation
const handleBkashValidate = (req: Request, res: Response) => {
  const customerId = (req.query.customer_id as string) || req.body.customer_id || req.body.username || req.body.phone;
  const result = PaymentGatewayService.validatePayBillCustomer(customerId);

  if (!result.success) {
    return res.status(404).json(result);
  }
  res.json(result);
};

router.get('/bkash/validate', handleBkashValidate);
router.post('/bkash/validate', handleBkashValidate);

// POST /api/bkash/confirm - bKash payment confirmation capture webhook
router.post('/bkash/confirm', async (req: Request, res: Response) => {
  try {
    const { trx_id, trxId, customer_id, customerId, amount, signature, timestamp } = req.body;

    const result = await PaymentGatewayService.confirmPayBillPayment({
      trxId: trx_id || trxId,
      customerId: customer_id || customerId,
      amount: Number(amount),
      signature,
      timestamp
    });

    res.json({
      success: true,
      statusCode: '0000',
      message: 'bKash Pay Bill confirmation processed. Subscriber renewed and unblocked.',
      data: result
    });
  } catch (err: any) {
    res.status(400).json({
      success: false,
      statusCode: '9999',
      errorCode: 'TRANSACTION_FAILED',
      errorMessage: err.message
    });
  }
});

// ==========================================
// 2. bKASH PERSONAL / AGENT SIM AUTOMATION WEBHOOK
// ==========================================

// POST /api/bkash-sim/webhook - Android Companion App SMS / Notification Webhook
router.post('/bkash-sim/webhook', async (req: Request, res: Response) => {
  try {
    const signature = req.headers['x-isp-signature'] as string || req.body.signature;
    const timestamp = req.headers['x-isp-timestamp'] as string || req.body.timestamp;

    const result = await PaymentGatewayService.processSimSmsWebhook({
      rawSmsOrNotification: req.body.rawSmsOrNotification || req.body.message || req.body.smsText,
      sender: req.body.sender,
      simSlot: req.body.simSlot,
      trxId: req.body.trxId || req.body.trx_id,
      amount: req.body.amount ? Number(req.body.amount) : undefined,
      reference: req.body.reference || req.body.ref,
      signature,
      timestamp
    });

    res.json({
      success: true,
      message: 'bKash SIM SMS alert parsed and verified. Subscriber extended successfully.',
      data: result
    });
  } catch (err: any) {
    res.status(400).json({
      success: false,
      message: err.message
    });
  }
});

// ==========================================
// 3. BILLING DESK & SELF-CARE HELPERS
// ==========================================

// GET /api/billing/desk/:subscriber_id - Customer Self-Care billing desk
router.get('/billing/desk/:subscriber_id', (req: Request, res: Response) => {
  try {
    const desk = BillingService.getCustomerBillingDesk(req.params.subscriber_id);
    res.json({ success: true, data: desk });
  } catch (err: any) {
    res.status(404).json({ success: false, message: err.message });
  }
});

// GET /api/packages - All ISP package tiers
router.get('/packages', (req: Request, res: Response) => {
  res.json({ success: true, data: db.packages });
});

// POST /api/subscribers/:id/shift-package - Self-Care package shift request
router.post('/subscribers/:id/shift-package', async (req: Request, res: Response) => {
  try {
    const { new_package_id } = req.body;
    const sub = db.subscribers.find(s => s.id === req.params.id || s.username === req.params.id);
    if (!sub) return res.status(404).json({ success: false, message: 'Subscriber not found' });

    const newPkg = db.packages.find(p => p.id === new_package_id);
    if (!newPkg) return res.status(400).json({ success: false, message: 'Invalid package selection' });

    const oldPkg = db.packages.find(p => p.id === sub.package_id);
    sub.package_id = newPkg.id;
    sub.updated_at = new Date().toISOString();

    db.logAudit('SUBSCRIBER', sub.id, 'PACKAGE_TIER_SHIFT', {
      username: sub.username,
      fromPackage: oldPkg?.name,
      toPackage: newPkg.name,
      newSpeed: newPkg.speed_mbps
    });

    db.persist();

    res.json({
      success: true,
      message: `Package shifted to '${newPkg.name}' (${newPkg.speed_mbps} Mbps). Will take effect on next billing cycle or instant reconnect.`,
      currentPackage: newPkg
    });
  } catch (err: any) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// GET /api/payments - Payment transaction history
router.get('/payments', (req: Request, res: Response) => {
  res.json({ success: true, count: db.payments.length, data: db.payments });
});

export const paymentRouter = router;
