/**
 * Currency Configuration Routes
 * Super Admin only — manages currency settings and exchange rates.
 */

import express, { Request, Response } from 'express';
import { authenticate, requireRole } from '../middleware/auth';
import { getModels } from '../models';

const router = express.Router();

// All routes require super-admin
router.use(authenticate, requireRole('super-admin'));

// GET / — List all currency configs
router.get('/', async (req: Request, res: Response) => {
  try {
    const { CurrencyConfig } = getModels();
    const currencies = await CurrencyConfig.find({}).sort({ isDefault: -1, code: 1 });

    // Seed defaults if empty
    if (currencies.length === 0) {
      const defaults = [
        { code: 'USD', name: 'US Dollar', symbol: '$', paymentGateway: 'stripe', isActive: true, isDefault: true, exchangeRateToUSD: 1 },
        { code: 'INR', name: 'Indian Rupee', symbol: '₹', paymentGateway: 'razorpay', isActive: true, isDefault: false, exchangeRateToUSD: 0.012 },
        { code: 'AED', name: 'UAE Dirham', symbol: 'د.إ', paymentGateway: 'stripe', isActive: true, isDefault: false, exchangeRateToUSD: 0.27 },
      ];
      await CurrencyConfig.insertMany(defaults);
      const seeded = await CurrencyConfig.find({}).sort({ isDefault: -1, code: 1 });
      res.json(seeded);
      return;
    }

    res.json(currencies);
  } catch (error) {
    console.error('Error fetching currency configs:', error);
    res.status(500).json({ error: 'Failed to fetch currency configurations' });
  }
});

// PUT /:id — Update currency config
router.put('/:id', async (req: Request, res: Response) => {
  try {
    const { CurrencyConfig } = getModels();
    const currency = await CurrencyConfig.findById(req.params.id);
    if (!currency) {
      res.status(404).json({ error: 'Currency config not found' });
      return;
    }

    const { isActive, isDefault, exchangeRateToUSD } = req.body;

    if (typeof isActive === 'boolean') currency.isActive = isActive;
    if (typeof isDefault === 'boolean') {
      // If setting as default, unset any other default
      if (isDefault) {
        await CurrencyConfig.updateMany({}, { isDefault: false });
      }
      currency.isDefault = isDefault;
    }
    if (typeof exchangeRateToUSD === 'number') currency.exchangeRateToUSD = exchangeRateToUSD;

    await currency.save();
    res.json(currency);
  } catch (error) {
    console.error('Error updating currency config:', error);
    res.status(500).json({ error: 'Failed to update currency configuration' });
  }
});

// POST / — Create a new currency config
router.post('/', async (req: Request, res: Response) => {
  try {
    const { CurrencyConfig } = getModels();
    const { code, name, symbol, paymentGateway, isActive, isDefault, exchangeRateToUSD } = req.body;

    if (!code || !name || !symbol || !paymentGateway) {
      res.status(400).json({ error: 'Code, name, symbol, and paymentGateway are required' });
      return;
    }

    // If setting as default, unset any other default
    if (isDefault) {
      await CurrencyConfig.updateMany({}, { isDefault: false });
    }

    const currency = new CurrencyConfig({
      code: code.toUpperCase(),
      name,
      symbol,
      paymentGateway,
      isActive: isActive ?? true,
      isDefault: isDefault ?? false,
      exchangeRateToUSD: exchangeRateToUSD ?? 1,
    });

    await currency.save();
    res.status(201).json(currency);
  } catch (error: any) {
    if (error.code === 11000) {
      res.status(409).json({ error: 'A currency with this code already exists' });
      return;
    }
    console.error('Error creating currency config:', error);
    res.status(500).json({ error: 'Failed to create currency configuration' });
  }
});

export default router;