import { NextRequest, NextResponse } from 'next/server';
import { requirePermission } from '@/shared/admin/guards';
import { PERMISSIONS } from '@/shared/admin/permissions';
import { assignRole, removeRole, getUserRoles } from '@/shared/admin/roles';
import { logAuditEvent } from '@/shared/admin/audit';

// --- ASA GENERATED START ---
// Route handler for admin/roles slice.
// GET: list user roles, POST: assign role, DELETE: remove role.
// Security: requires admin.roles.assign permission (server-side).
// --- ASA GENERATED END ---

// --- USER CODE START ---

export async function GET(request: NextRequest): Promise<NextResponse> {
  const { response } = await requirePermission(request, PERMISSIONS.ROLES_ASSIGN);
  if (response) return response;

  const url = new URL(request.url);
  const userId = url.searchParams.get('user_id');

  if (!userId) {
    return NextResponse.json({ error: 'user_id is required' }, { status: 400 });
  }

  const roles = await getUserRoles(userId);
  return NextResponse.json({ user_id: userId, roles });
}

export async function POST(request: NextRequest): Promise<NextResponse> {
  const { user, response } = await requirePermission(request, PERMISSIONS.ROLES_ASSIGN);
  if (response) return response;

  const body = await request.json();
  const { user_id, role_id } = body;

  if (!user_id || !role_id) {
    return NextResponse.json(
      { success: false, error: 'user_id and role_id are required' },
      { status: 400 },
    );
  }

  const result = await assignRole(user_id, role_id, user!.id);

  if (result.success) {
    await logAuditEvent({
      actor_id: user!.id,
      actor_email: user!.email,
      subject_id: user_id,
      action: 'role.assign',
      resource_type: 'role',
      resource_id: role_id,
    });
  }

  return NextResponse.json(result, { status: result.success ? 200 : 400 });
}

export async function DELETE(request: NextRequest): Promise<NextResponse> {
  const { user, response } = await requirePermission(request, PERMISSIONS.ROLES_ASSIGN);
  if (response) return response;

  const body = await request.json();
  const { user_id, role_id } = body;

  if (!user_id || !role_id) {
    return NextResponse.json(
      { success: false, error: 'user_id and role_id are required' },
      { status: 400 },
    );
  }

  const result = await removeRole(user_id, role_id);

  if (result.success) {
    await logAuditEvent({
      actor_id: user!.id,
      actor_email: user!.email,
      subject_id: user_id,
      action: 'role.remove',
      resource_type: 'role',
      resource_id: role_id,
    });
  }

  return NextResponse.json(result, { status: result.success ? 200 : 400 });
}

// --- USER CODE END ---
