import { NextRequest, NextResponse } from 'next/server';
import { listUserPermissionAssignmentsForOrganization } from '@/features/permission-management/server/user-permission-data';
import { AuthError, requireSuperAdminOrganizationAccess } from '@/lib/auth/session';

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireSuperAdminOrganizationAccess();
    const result = await listUserPermissionAssignmentsForOrganization({
      organizationId: organization.id,
      filters: {
        page: Number(request.nextUrl.searchParams.get('page') ?? 1),
        limit: Number(request.nextUrl.searchParams.get('limit') ?? 10),
        search: request.nextUrl.searchParams.get('search') ?? undefined,
        sort: request.nextUrl.searchParams.get('sort') ?? undefined
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Loaded user permission assignments successfully',
      total_user_permissions: result.total,
      offset: result.offset,
      limit: result.limit,
      user_permissions: result.userPermissions
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to load user permissions' }, { status: 500 });
  }
}
