import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest, requireSection } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createRoleSchema, type CreateRoleInput } from '@server/validators/roles.validator';
import { listRoles, createRole } from '@server/services/roles.service';

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

    const roles = await listRoles({ restaurantId: req.session.restaurantId! });
    return NextResponse.json({ roles });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createRoleSchema, async (req) => {
      await requireSection(req, 'staff', 'create');

      const body = req.parsedBody as CreateRoleInput;
      const role = await createRole(req.session.restaurantId!, {
        name: body.name,
        description: body.description,
        permissions: body.permissions,
      });
      return NextResponse.json({ role }, { status: 201 });
    })
  )
);
