import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { initDatabase } from '@server/db/init';

/**
 * Returns the active Stripe publishable key using the same priority as the
 * server-side secret key resolver:
 * 1. DB mode-aware lookup (stripe_mode controls which bucket is used)
 * 2. NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY env var — fallback only when no DB
 *    publishable key of any kind is configured.
 */
export const GET = withErrorHandler(async () => {
  await initDatabase();

  try {
    const { getPlatformSettings } = await import('@server/services/admin.service');
    const settings = await getPlatformSettings();

    const modeExplicit = settings.stripe_mode as 'test' | 'live' | undefined;
    const testPub = settings.stripe_test_publishable_key as string | undefined;
    const livePub = settings.stripe_live_publishable_key as string | undefined;
    const legacyPub = settings.stripe_publishable_key as string | undefined;

    if (modeExplicit) {
      // Strict: only the bucket matching the explicit mode
      const publishableKey = (modeExplicit === 'test' ? testPub : livePub) ?? null;
      return NextResponse.json({ publishableKey });
    }

    // Mode not yet set: infer from available bucket keys
    if (testPub && !livePub) return NextResponse.json({ publishableKey: testPub });
    if (livePub && !testPub) return NextResponse.json({ publishableKey: livePub });
    if (livePub) return NextResponse.json({ publishableKey: livePub });

    // Pre-migration legacy key
    if (legacyPub) return NextResponse.json({ publishableKey: legacyPub });

    // Last resort: env var (no DB keys configured at all)
    const envKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;
    return NextResponse.json({ publishableKey: envKey ?? null });
  } catch {
    // On DB error fall back to env var so the checkout page can still render
    const envKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;
    return NextResponse.json({ publishableKey: envKey ?? null });
  }
});
