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

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireSuperAdminOrganizationAccess();
    const result = await listPermissionAuditLogsForOrganization({
      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,
        user: request.nextUrl.searchParams.get('user') ?? undefined,
        action: request.nextUrl.searchParams.get('action') ?? undefined,
        dateFrom: request.nextUrl.searchParams.get('dateFrom') ?? undefined,
        dateTo: request.nextUrl.searchParams.get('dateTo') ?? undefined,
        sort: request.nextUrl.searchParams.get('sort') ?? undefined
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Loaded permission audit logs successfully',
      total_permission_audit_logs: result.total,
      offset: result.offset,
      limit: result.limit,
      permission_audit_logs: result.permissionAuditLogs
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to load permission audit logs' }, { status: 500 });
  }
}
