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 { updateStaffSchema } from '@server/validators/staff.validator';
import { getStaffMember, updateStaffMember, deactivateStaffMember, deleteStaffMember } from '@server/services/staff.service';

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

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateStaffSchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;

      if (req.parsedBody.is_active === false) {
        const member = await deactivateStaffMember(id, req.session.restaurantId!);
        return NextResponse.json({ staff: member });
      }

      const member = await updateStaffMember(id, req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ staff: member });
    })
  )
);

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