import { Router } from 'express';

import { getExchangeRateService } from '../libs/exchange-rate/service';
import { getExchangeRateSymbol, hasTokenAddress } from '../libs/exchange-rate/token-address-mapping';
import { authenticate } from '../libs/security';
import { ChainType, PaymentCurrency, PaymentMethod } from '../store/models';

const router = Router();
const auth = authenticate({ component: true, roles: ['owner', 'admin'], ensureLogin: true });
const exchangeRateService = getExchangeRateService();

/**
 * Validate if exchange rate can be fetched for a currency
 * This is used during price creation/editing to validate the base currency
 */
router.post('/validate', auth, async (req, res) => {
  try {
    const { currency: currencyId } = req.body;

    if (!currencyId) {
      return res.status(400).json({ error: 'currency is required' });
    }

    const paymentCurrency = (await PaymentCurrency.findByPk(currencyId, {
      include: [
        {
          model: PaymentMethod,
          as: 'payment_method',
        },
      ],
    })) as PaymentCurrency & { payment_method: PaymentMethod };

    if (!paymentCurrency) {
      return res.status(400).json({ error: 'Currency not found' });
    }

    if (paymentCurrency.payment_method?.type === 'stripe') {
      return res.status(400).json({
        error: `Currency ${paymentCurrency.symbol} is not supported.`,
        supported: false,
      });
    }

    // Check if token has address mapping
    if (!hasTokenAddress(paymentCurrency.symbol, paymentCurrency.payment_method?.type as ChainType)) {
      return res.status(400).json({
        error: `Currency ${paymentCurrency.symbol} is not supported.`,
        supported: false,
      });
    }

    // Try to fetch exchange rate
    try {
      const rateSymbol = getExchangeRateSymbol(
        paymentCurrency.symbol,
        paymentCurrency.payment_method?.type as ChainType
      );
      const rateResult = await exchangeRateService.getRate(rateSymbol);

      // Return full rate info consistent with checkout-sessions exchange-rate endpoint
      return res.json({
        supported: true,
        currency: paymentCurrency.symbol,
        base_currency: 'USD',
        rate: rateResult.rate,
        timestamp_ms: rateResult.timestamp_ms,
        fetched_at: rateResult.fetched_at,
        provider_id: rateResult.provider_id,
        provider_name: rateResult.provider_name,
        provider_display: rateResult.provider_display,
        providers: rateResult.providers,
        consensus_method: rateResult.consensus_method,
        degraded: rateResult.degraded,
        degraded_reason: rateResult.degraded_reason,
      });
    } catch (error: any) {
      return res.status(400).json({
        error: `Failed to fetch exchange rate for ${paymentCurrency.symbol}: ${error.message}`,
        supported: false,
      });
    }
  } catch (error: any) {
    return res.status(400).json({ error: error.message });
  }
});

export default router;
