import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { getActiveGateways } from '@server/services/gateway.service';
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';
import { initDatabase } from '@server/db/init';

export const GET = withErrorHandler(
  withAuth(async (_req: AuthedRequest) => {
    await initDatabase();

    const [gateways, { rows: priceRows }] = await Promise.all([
      getActiveGateways(),
      db.execute(sql`
        SELECT DISTINCT pp.currency_code
        FROM public.plan_prices pp
        JOIN public.plans p ON p.id = pp.plan_id
        WHERE p.is_active = true
        ORDER BY pp.currency_code ASC
      `),
    ]);

    const gwCurrencies = gateways.map(g => g.currency.toUpperCase());
    const planCurrencies = (priceRows as { currency_code: string }[]).map(r => r.currency_code.toUpperCase());

    const allCurrencies = [...new Set([...gwCurrencies, ...planCurrencies])].sort();

    return NextResponse.json({ currencies: allCurrencies });
  })
);
