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

export const GET = withErrorHandler(async () => {
  await initDatabase();

  const envKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;
  if (envKey) {
    return NextResponse.json({ publishableKey: envKey });
  }

  try {
    const { getPlatformSettings } = await import('@server/services/admin.service');
    const settings = await getPlatformSettings();
    const dbKey = settings.stripe_publishable_key as string | undefined;
    if (dbKey) {
      return NextResponse.json({ publishableKey: dbKey });
    }
  } catch {
  }

  return NextResponse.json({ publishableKey: null });
});
