import { Router, Request, Response } from 'express';
import { db, Reseller } from '../../database/db';
import { WalletService } from '../billing/wallet.service';

const router = Router();

// GET /api/resellers - List resellers with wallet & subscriber statistics
router.get('/', (req: Request, res: Response) => {
  const resellers = db.resellers.map(r => {
    const summary = WalletService.getWalletSummary(r.id);
    return {
      ...r,
      wallet_balance: summary.wallet.balance,
      currency: summary.wallet.currency,
      total_subscribers: summary.totalSubscribers,
      active_subscribers: summary.activeSubscribers,
      expired_subscribers: summary.expiredSubscribers
    };
  });

  res.json({ success: true, data: resellers });
});

// GET /api/resellers/:id/wallet - Get wallet and ledger statement
router.get('/:id/wallet', (req: Request, res: Response) => {
  try {
    const summary = WalletService.getWalletSummary(req.params.id);
    res.json({ success: true, data: summary });
  } catch (err: any) {
    res.status(404).json({ success: false, message: err.message });
  }
});

// POST /api/resellers/:id/topup - Top up reseller pre-paid wallet
router.post('/:id/topup', async (req: Request, res: Response) => {
  try {
    const { amount, reference_id, description } = req.body;
    if (!amount || Number(amount) <= 0) {
      return res.status(400).json({ success: false, message: 'Valid positive amount is required.' });
    }

    const result = await WalletService.topupWallet(
      req.params.id,
      Number(amount),
      reference_id || `MANUAL_TOPUP_${Date.now()}`,
      description || 'Super Admin Manual Wallet Top-Up'
    );

    res.json({
      success: true,
      message: `Successfully topped up ৳${amount} to reseller wallet.`,
      data: result
    });
  } catch (err: any) {
    res.status(500).json({ success: false, message: err.message });
  }
});

// GET /api/resellers/:id/packages - Get wholesale packages with reseller's retail markup
router.get('/:id/packages', (req: Request, res: Response) => {
  const resellerId = req.params.id;
  const packages = db.packages.map(p => {
    const custom = db.reseller_packages.find(rp => rp.reseller_id === resellerId && rp.package_id === p.id);
    return {
      package_id: p.id,
      package_name: p.name,
      speed_mbps: p.speed_mbps,
      wholesale_price: p.wholesale_price,
      default_retail_price: p.default_retail_price,
      custom_retail_price: custom ? custom.custom_retail_price : p.default_retail_price,
      margin_profit: (custom ? custom.custom_retail_price : p.default_retail_price) - p.wholesale_price
    };
  });

  res.json({ success: true, data: packages });
});

// POST /api/resellers/:id/packages - Set custom retail markup
router.post('/:id/packages', (req: Request, res: Response) => {
  const resellerId = req.params.id;
  const { package_id, custom_retail_price } = req.body;

  if (!package_id || custom_retail_price === undefined) {
    return res.status(400).json({ success: false, message: 'package_id and custom_retail_price required' });
  }

  let custom = db.reseller_packages.find(rp => rp.reseller_id === resellerId && rp.package_id === package_id);
  if (custom) {
    custom.custom_retail_price = Number(custom_retail_price);
  } else {
    custom = {
      id: `rp_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`,
      reseller_id: resellerId,
      package_id,
      custom_retail_price: Number(custom_retail_price),
      status: 'active'
    };
    db.reseller_packages.push(custom);
  }

  db.persist();
  res.json({ success: true, message: 'Custom retail price configured.', data: custom });
});

export const resellerRouter = router;
