import { NextResponse } from 'next/server';
import { db, restaurants } from '@server/db/drizzle';
import { eq } from 'drizzle-orm';
import { initDatabase } from '@server/db/init';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { seedNoidaMenu, findOrCreateNoidaBranch } from '@server/data/noida-menu-seed';

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();

    const { restaurantId } = req.session;

    const rows = await db.select({ id: restaurants.id, name: restaurants.name })
      .from(restaurants)
      .where(eq(restaurants.id, restaurantId!));
    const restaurant = rows[0];

    if (!restaurant || restaurant.name !== 'The Rustic Fork') {
      return NextResponse.json(
        { ok: false, error: 'This endpoint is only available for the demo restaurant.' },
        { status: 403 }
      );
    }

    let body: { force?: boolean } = {};
    try { body = await req.json(); } catch { /* no body is fine */ }

    const branchId = await findOrCreateNoidaBranch(restaurant.id);
    const result = await seedNoidaMenu(restaurant.id, branchId, body.force === true);

    return NextResponse.json({
      ok: true,
      restaurantId: restaurant.id,
      branchId,
      ...result,
      message:
        result.categoriesSeeded === 0
          ? 'Menu already seeded — no duplicates created.'
          : `Seeded ${result.categoriesSeeded} categories and ${result.itemsSeeded} items.`,
    });
  })
);
