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 { updateTableSchema } from '@server/validators/tables.validator';
import { getTable, updateTable, deleteTable } from '@server/services/tables.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    const table = await getTable(id, req.session.restaurantId!);
    return NextResponse.json({ table });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateTableSchema, async (req, ctx: RouteContext) => {
      await requirePlanFeature(req.session.restaurantId!, 'storefront');
      const { id } = await ctx.params;
      const table = await updateTable(id, req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ table });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requirePlanFeature(req.session.restaurantId!, 'storefront');
    const { id } = await ctx.params;
    await deleteTable(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
