import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { db, restaurants } from '@server/db/drizzle';
import { eq, and, isNull, sql } from 'drizzle-orm';
import { initDatabase } from '@server/db/init';

const VALID_CURRENCIES = new Set([
  'USD','EUR','GBP','INR','AED','SAR','CAD','AUD','SGD','MYR',
  'THB','PHP','IDR','JPY','KRW','CNY','HKD','TWD','NZD','ZAR',
  'BRL','MXN','CLP','COP','ARS','PEN','TRY','EGP','NGN','KES',
  'GHS','PKR','BDT','LKR','NPR','QAR','KWD','BHD','OMR','JOD',
  'CHF','SEK','NOK','DKK','PLN','CZK','HUF','RON','RUB','UAH',
  'ILS','VND','MMK','KHR','LAK',
]);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();
    const { restaurantId } = req.session;
    if (!restaurantId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json().catch(() => ({}));
    const { currency } = body as { currency?: string };
    if (!currency || typeof currency !== 'string') {
      return NextResponse.json({ error: 'Currency code is required' }, { status: 400 });
    }

    const code = currency.toUpperCase().trim();
    if (!VALID_CURRENCIES.has(code)) {
      return NextResponse.json({ error: 'Invalid currency code' }, { status: 400 });
    }

    const rows = await db.update(restaurants)
      .set({ currency: code, currencySetAt: sql`NOW()`, updatedAt: sql`NOW()` })
      .where(and(eq(restaurants.id, restaurantId), isNull(restaurants.currencySetAt)))
      .returning({ currency: restaurants.currency });
    const result = rows[0];

    if (!result) {
      return NextResponse.json(
        { error: 'Currency has already been set and cannot be changed. Contact support if needed.' },
        { status: 409 }
      );
    }

    return NextResponse.json({ currency: result.currency });
  })
);
