import { Router } from 'express';

import { PaymentCurrency } from '../store/models/payment-currency';
import autoRechargeConfigs from './auto-recharge-configs';
import checkoutSessions from './checkout-sessions';
import coupons from './coupons';
import creditGrants from './credit-grants';
import creditTokens from './credit-tokens';
import creditTransactions from './credit-transactions';
import customers from './customers';
import donations from './donations';
import events from './events';
import stripe from './integrations/stripe';
import invoices from './invoices';
import meterEvents from './meter-events';
import taxRates from './tax-rates';
import meters from './meters';
import passports from './passports';
import paymentCurrencies from './payment-currencies';
import paymentIntents from './payment-intents';
import paymentLinks from './payment-links';
import paymentMethods from './payment-methods';
import paymentStats from './payment-stats';
import payouts from './payouts';
import prices from './prices';
import pricingTables from './pricing-table';
import products from './products';
import promotionCodes from './promotion-codes';
import redirect from './redirect';
import refunds from './refunds';
import exchangeRateProviders from './exchange-rate-providers';
import exchangeRates from './exchange-rates';
import settings from './settings';
import subscriptionItems from './subscription-items';
import subscriptions from './subscriptions';
import usageRecords from './usage-records';
import webhookAttempts from './webhook-attempts';
import webhookEndpoints from './webhook-endpoints';
import vendor from './vendor';
import tool from './tool';
import archive from './archive';

const router = Router();

router.use((req, _, next) => {
  if (req.query.livemode) {
    try {
      req.livemode = !!JSON.parse(String(req.query.livemode));
    } catch {
      req.livemode = true;
    }
  } else {
    req.livemode = true;
  }

  next();
});

// Lazy-load base currency with TTL cache to avoid DB query on every request
const baseCurrencyCache = new Map<string, { data: any; expires: number }>();
const BASE_CURRENCY_TTL = 5 * 60_000; // 5 minutes (invalidated on model update)

// Lazily register hooks after models are initialized (avoid top-level addHook before Sequelize init)
let baseCurrencyHooksRegistered = false;
function ensureBaseCurrencyHooks() {
  if (baseCurrencyHooksRegistered) return;
  baseCurrencyHooksRegistered = true;
  PaymentCurrency.addHook('afterUpdate', 'invalidateBaseCurrencyCache', () => {
    baseCurrencyCache.clear();
  });
  PaymentCurrency.addHook('afterDestroy', 'invalidateBaseCurrencyCacheOnDelete', () => {
    baseCurrencyCache.clear();
  });
}

// Base currency middleware — only needed by routes that use req.currency
// (checkout-sessions, donations, payment-links, prices, products)
const loadBaseCurrency = async (req: any, _: any, next: any) => {
  ensureBaseCurrencyHooks();
  const key = `base_${req.livemode}`;
  const cached = baseCurrencyCache.get(key);
  if (cached && cached.expires > Date.now()) {
    req.baseCurrency = cached.data;
  } else {
    req.baseCurrency = await PaymentCurrency.findOne({ where: { is_base_currency: true, livemode: req.livemode } });
    if (req.baseCurrency) {
      baseCurrencyCache.set(key, { data: req.baseCurrency, expires: Date.now() + BASE_CURRENCY_TTL });
    }
  }
  next();
};

router.use('/auto-recharge-configs', autoRechargeConfigs);
router.use('/checkout-sessions', loadBaseCurrency, checkoutSessions);
router.use('/coupons', coupons);
router.use('/credit-grants', creditGrants);
router.use('/credit-tokens', creditTokens);
router.use('/credit-transactions', creditTransactions);
router.use('/customers', customers);
router.use('/donations', loadBaseCurrency, donations);
router.use('/events', events);
router.use('/invoices', invoices);
router.use('/integrations/stripe', stripe);
router.use('/meter-events', meterEvents);
router.use('/meters', meters);
router.use('/passports', passports);
router.use('/payment-intents', paymentIntents);
router.use('/payment-links', loadBaseCurrency, paymentLinks);
router.use('/payment-methods', paymentMethods);
router.use('/payment-currencies', paymentCurrencies);
router.use('/payment-stats', paymentStats);
router.use('/prices', loadBaseCurrency, prices);
router.use('/pricing-tables', pricingTables);
router.use('/tax-rates', taxRates);
router.use('/products', loadBaseCurrency, products);
router.use('/promotion-codes', promotionCodes);
router.use('/exchange-rate-providers', exchangeRateProviders);
router.use('/exchange-rates', exchangeRates);
router.use('/payouts', payouts);
router.use('/redirect', redirect);
router.use('/refunds', refunds);
router.use('/settings', settings);
router.use('/subscription-items', subscriptionItems);
router.use('/subscriptions', subscriptions);
router.use('/usage-records', usageRecords);
router.use('/webhook-attempts', webhookAttempts);
router.use('/webhook-endpoints', webhookEndpoints);
router.use('/vendors', vendor);
router.use('/tool', tool);
router.use('/archive', archive);

export default router;
