import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ValidationError } from '@server/errors';
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';
import { initDatabase } from '@server/db/init';
import { childLogger } from '@server/logger';

const log = childLogger('route.billing.billing-contact');

export const PATCH = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();
    const restaurantId = req.session.restaurantId!;
    let _body: Awaited<ReturnType<typeof req.json>>;
    try {
      _body = await req.json();
    } catch {
      throw new ValidationError('Request body must be valid JSON');
    }
    const { billingContactEmail } = _body;

    await db.execute(sql`
      INSERT INTO public.subscriptions (restaurant_id, billing_contact_email, status, trial_end)
      VALUES (${restaurantId}, ${billingContactEmail ?? null}, 'trial', NOW())
      ON CONFLICT (restaurant_id) DO UPDATE SET
        billing_contact_email = EXCLUDED.billing_contact_email
    `);

    if (billingContactEmail?.trim()) {
      try {
        const { getStripeClientFromDb, getStripeSecretKey } = await import('@server/lib/stripe');
        const stripeKey = await getStripeSecretKey();
        if (stripeKey) {
          const stripe = await getStripeClientFromDb();
          const { rows } = await db.execute(sql`
            SELECT stripe_customer_id FROM public.subscriptions WHERE restaurant_id = ${restaurantId} LIMIT 1
          `);
          const customerId = (rows[0] as { stripe_customer_id: string | null } | undefined)?.stripe_customer_id;
          if (customerId) {
            await stripe.customers.update(customerId, {
              metadata: { billing_contact_email: billingContactEmail.trim() },
            });
          }
        }
      } catch (err) {
        log.warn({ err }, 'billing-contact: failed to update Stripe customer metadata, continuing');
      }
    }

    return NextResponse.json({ ok: true });
  })
);

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();
    const restaurantId = req.session.restaurantId!;

    const { rows } = await db.execute(sql`
      SELECT billing_contact_email FROM public.subscriptions
      WHERE restaurant_id = ${restaurantId}
      LIMIT 1
    `);

    const row = rows[0] as { billing_contact_email: string | null } | undefined;
    return NextResponse.json({ billingContactEmail: row?.billing_contact_email ?? null });
  })
);
