import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createTableSchema, bulkCreateTablesSchema } from '@server/validators/tables.validator';
import { listTables, createTable, bulkCreateTables } from '@server/services/tables.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await requirePlanFeature(req.session.restaurantId!, 'storefront');
    const url = new URL(req.url);
    const branchId = url.searchParams.get('branch_id') ?? undefined;
    const tables = await listTables(req.session.restaurantId!, branchId);
    return NextResponse.json({ tables });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createTableSchema, async (req, _ctx: RouteContext) => {
      await requirePlanFeature(req.session.restaurantId!, 'storefront');
      const table = await createTable(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ table }, { status: 201 });
    })
  )
);

export const PUT = withErrorHandler(
  withAuth(
    withValidationAuthed(bulkCreateTablesSchema, async (req) => {
      await requirePlanFeature(req.session.restaurantId!, 'storefront');
      const body = req.parsedBody as { branch_id: string; start: number; end: number; prefix?: string; capacity?: number; zone?: string | null };
      const numbers: string[] = [];
      const prefix = body.prefix ?? '';
      for (let i = body.start; i <= body.end; i++) {
        numbers.push(`${prefix}${i}`);
      }
      const created = await bulkCreateTables(req.session.restaurantId!, body.branch_id, numbers, { capacity: body.capacity, zone: body.zone ?? undefined });
      return NextResponse.json({ tables: created, created: created.length, requested: numbers.length });
    })
  )
);
