import { NextResponse } from 'next/server';

import { withAuth, withPermission, requireSuperAdmin } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { getRole, updateRole, deleteRole } from '@/lib/services/roles.service';
import { updateRoleSchema } from '@/lib/validators/roles';
import { errorResponse } from '@/lib/errors';

export const GET = withAuth(
  withPermission('admin', 'manage_users', async (_req, _ctx, params) => {
    try {
      const data = await getRole(params.id!);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

// Mutations on global roles are super-admin-only - see route.ts header.
export const PATCH = withAuth(async (req, ctx, params) => {
  try {
    requireSuperAdmin(ctx, 'roles.update');
    const body = await parseBody(req, updateRoleSchema);
    const data = await updateRole(params.id!, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data });
  } catch (error) {
    return errorResponse(error);
  }
});

export const DELETE = withAuth(async (_req, ctx, params) => {
  try {
    requireSuperAdmin(ctx, 'roles.delete');
    await deleteRole(params.id!, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return new NextResponse(null, { status: 204 });
  } catch (error) {
    return errorResponse(error);
  }
});
