import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest, requireSection } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateRoleSchema, type UpdateRoleInput } from '@server/validators/roles.validator';
import { getRole, updateRole, deleteRole } from '@server/services/roles.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'staff', 'read');

    const { id } = await ctx.params;
    const role = await getRole(id, req.session.restaurantId!);
    return NextResponse.json({ role });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateRoleSchema, async (req, ctx: RouteContext) => {
      await requireSection(req, 'staff', 'update');

      const { id } = await ctx.params;
      const body = req.parsedBody as UpdateRoleInput;
      const role = await updateRole(id, req.session.restaurantId!, {
        name: body.name,
        description: body.description,
        permissions: body.permissions,
      });
      return NextResponse.json({ role });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'staff', 'delete');

    const { id } = await ctx.params;
    await deleteRole(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
