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 { updateCustomerSchema } from '@server/validators/customers.validator';
import { getCustomer, updateCustomer, deleteCustomer } from '@server/services/customers.service';

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

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateCustomerSchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;
      const customer = await updateCustomer(id, req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ customer });
    })
  )
);

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