import { NextResponse } from 'next/server';

import { withAuth, withPermission, requireSuperAdmin } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { listRoles, createRole } from '@/lib/services/roles.service';
import { createRoleSchema } from '@/lib/validators/roles';
import { errorResponse } from '@/lib/errors';

export const GET = withAuth(
  withPermission('admin', 'manage_users', async () => {
    try {
      const data = await listRoles();
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

// Roles are global (no port_id) and assignments span every port via
// userPortRoles, so creation must be super-admin-only - a per-port admin
// holding admin.manage_users must never be able to mint a role that lives
// in another tenant.
export const POST = withAuth(async (req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'roles.create');
    const body = await parseBody(req, createRoleSchema);
    const data = await createRole(body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
});
