import { NextRequest, NextResponse } from 'next/server';
import { auditAction } from '@/features/foundation/audit-log/service';
import { AuthError } from '@/lib/auth/session';
import {
  assertManageableTargetUser,
  buildUserResponseModels,
  requireUserManagementAccess
} from '@/app/api/users/_lib';

type Params = {
  params: Promise<{ id: string }>;
};

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { session, isSuperAdmin, manageableOrganizationIds } = await requireUserManagementAccess();
    await assertManageableTargetUser(id, manageableOrganizationIds, isSuperAdmin);
    const [user] = await buildUserResponseModels({
      scopedUserIds: [id],
      ...(isSuperAdmin ? {} : { scopedOrganizationIds: manageableOrganizationIds })
    });

    if (!user) {
      return NextResponse.json({ message: 'User not found' }, { status: 404 });
    }

    await auditAction({
      organizationId: session.user.activeOrganizationId ?? user.organizations[0]?.id,
      userId: session.user.id,
      entityType: 'effective_access_preview',
      entityId: id,
      action: 'preview',
      afterData: {
        userId: user.id,
        crmAccessSummaries: user.crmAccessSummaries
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Effective access preview loaded successfully',
      user
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to preview effective access' }, { status: 500 });
  }
}
