import { NextRequest, NextResponse } from 'next/server';
import { requirePermission } from '@/shared/admin/guards';
import { PERMISSIONS } from '@/shared/admin/permissions';
import { createAdminClient } from '@/shared/db/supabase-client';

// --- ASA GENERATED START ---
// Route handler for admin/users slice.
// Lists users with their profiles and roles.
// Security: requires admin.users.list permission (server-side).
// --- ASA GENERATED END ---

// --- USER CODE START ---

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

  const supabase = createAdminClient();
  const url = new URL(request.url);
  const page = parseInt(url.searchParams.get('page') ?? '1');
  const limit = Math.min(parseInt(url.searchParams.get('limit') ?? '50'), 100);
  const search = url.searchParams.get('search') ?? '';

  let query = supabase
    .from('profiles')
    .select('id, display_name, role, created_at, updated_at', { count: 'exact' })
    .order('created_at', { ascending: false })
    .range((page - 1) * limit, page * limit - 1);

  if (search) {
    query = query.or(`display_name.ilike.%${search}%`);
  }

  const { data: profiles, count, error } = await query;

  if (error) {
    return NextResponse.json({ error: 'Failed to fetch users' }, { status: 500 });
  }

  return NextResponse.json({
    users: profiles ?? [],
    total: count ?? 0,
    page,
    limit,
  });
}

// --- USER CODE END ---
