<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\BulkUploadEmployeeRegistrationRequest;
use App\Http\Requests\SendInvitationRequest;
use App\Http\Requests\UpdateEmployeeRegistrationRequest;
use App\Models\AuditLog;
use App\Models\EmployeeRegistration;
use App\Services\AmlScreeningService;
use App\Services\AuditService;
use App\Services\BulkEmployeeRegistrationUploadService;
use App\Services\EmployeeRegistrationService;
use App\Services\RegistrationFileUploadService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class EmployeeRegistrationController extends Controller
{
    public function __construct(
        private readonly EmployeeRegistrationService $registrationService,
        private readonly RegistrationFileUploadService $fileUploadService,
        private readonly BulkEmployeeRegistrationUploadService $bulkUploadService,
        private readonly AuditService $auditService,
        private readonly AmlScreeningService $amlScreeningService,
    ) {}

    /**
     * Get all pending Employee registrations.
     */
    public function pending(Request $request): JsonResponse
    {
        try {
            $perPage = (int) $request->input('per_page', 15);
            $perPage = min(max($perPage, 1), 100);

            $submissions = $this->registrationService->getPendingSubmissions($perPage);

            return response()->json([
                'success' => true,
                'data' => $submissions->items() ? collect($submissions->items())->map(fn ($submission) => [
                    'id' => $submission->id,
                    'company_id' => $submission->company_id,
                    'company_name' => $submission->company?->name,
                    'first_name' => $submission->first_name,
                    'last_name' => $submission->last_name,
                    'email_address' => $submission->email_address,
                    'phone_number' => $submission->phone_number,
                    'country' => $submission->country,
                    'state' => $submission->state,
                    'city' => $submission->city,
                    'submission_type' => $submission->submission_type,
                    'status' => $submission->status,
                    'account_status' => $submission->account_status,
                    'verification_status' => $submission->verification_status,
                    'submitted_at' => $submission->created_at->toIso8601String(),
                ]) : [],
                'pagination' => [
                    'current_page' => $submissions->currentPage(),
                    'last_page' => $submissions->lastPage(),
                    'per_page' => $submissions->perPage(),
                    'total' => $submissions->total(),
                    'from' => $submissions->firstItem() ?? 0,
                    'to' => $submissions->lastItem() ?? 0,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching pending Employee registrations: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching pending submissions.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Get all Employee registrations with optional filters.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $perPage = (int) $request->input('per_page', 15);
            $perPage = min(max($perPage, 1), 100);

            $filters = [];
            if ($request->has('status')) {
                $filters['status'] = $request->input('status');
            }
            if ($request->has('submission_type')) {
                $filters['submission_type'] = $request->input('submission_type');
            }
            if ($request->has('company_id')) {
                $filters['company_id'] = $request->input('company_id');
            }
            if ($request->has('from_date')) {
                $filters['from_date'] = $request->input('from_date');
            }
            if ($request->has('to_date')) {
                $filters['to_date'] = $request->input('to_date');
            }

            $submissions = $this->registrationService->getAllSubmissions($filters, $perPage);

            return response()->json([
                'success' => true,
                'data' => $submissions->items() ? collect($submissions->items())->map(fn ($submission) => [
                    'id' => $submission->id,
                    'company_id' => $submission->company_id,
                    'company_name' => $submission->company?->name,
                    'first_name' => $submission->first_name,
                    'last_name' => $submission->last_name,
                    'email_address' => $submission->email_address,
                    'phone_number' => $submission->phone_number,
                    'country' => $submission->country,
                    'state' => $submission->state,
                    'city' => $submission->city,
                    'submission_type' => $submission->submission_type,
                    'status' => $submission->status,
                    'account_status' => $submission->account_status,
                    'verification_status' => $submission->verification_status,
                    'submitted_at' => $submission->created_at->toIso8601String(),
                    'approved_at' => $submission->approved_at?->toIso8601String(),
                    'rejected_at' => $submission->rejected_at?->toIso8601String(),
                ]) : [],
                'pagination' => [
                    'current_page' => $submissions->currentPage(),
                    'last_page' => $submissions->lastPage(),
                    'per_page' => $submissions->perPage(),
                    'total' => $submissions->total(),
                    'from' => $submissions->firstItem() ?? 0,
                    'to' => $submissions->lastItem() ?? 0,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching Employee registrations: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching submissions.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Get a specific Employee registration.
     */
    public function show(EmployeeRegistration $registration, Request $request): JsonResponse
    {
        try {
            $registration = $this->registrationService->getSubmission($registration);

            $this->auditService->success(
                AuditLog::ACTION_EMPLOYEE_REGISTRATION_VIEWED,
                AuditLog::ACTOR_ADMIN,
                $request->user()->id,
                $request->user()->email,
                'EmployeeRegistration', $registration->id,
                ['name' => $registration->first_name . ' ' . $registration->last_name],
                $request->ip(),
            );

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $registration->id,
                    'company_id' => $registration->company_id,
                    'company_employee_id' => $registration->company_employee_id,
                    'submission_type' => $registration->submission_type,
                    'status' => $registration->status,
                    'account_status' => $registration->account_status,
                    'verification_status' => $registration->verification_status,
                    'rejection_reason' => $registration->rejection_reason,
                    // BIO-DATA INFORMATION
                    'title' => $registration->title,
                    'first_name' => $registration->first_name,
                    'last_name' => $registration->last_name,
                    'middle_name' => $registration->middle_name,
                    'gender' => $registration->gender,
                    'date_of_birth' => $registration->date_of_birth?->toDateString(),
                    'nationality' => $registration->nationality,
                    'phone_number' => $registration->phone_number,
                    'foreign_number' => $registration->foreign_number,
                    'email_address' => $registration->email_address,
                    'country' => $registration->country,
                    'state' => $registration->state,
                    'city' => $registration->city,
                    'chn' => $registration->chn,
                    'house_address' => $registration->house_address,
                    'previous_address' => $registration->previous_address,
                    // BANK INFORMATION
                    'bank_name' => $registration->bank_name,
                    'bank_account_number' => $registration->bank_account_number,
                    'tin_or_pin' => $registration->tin_or_pin,
                    'bank_details_consent' => $registration->bank_details_consent,
                    // IDENTITY INFORMATION
                    'identity_card_type' => $registration->identity_card_type,
                    'identity_card_number' => $registration->identity_card_number,
                    // Document URLs
                    'documents' => [
                        'identity_card' => $this->fileUploadService->getEmployeeDocumentUrl($registration->identity_card_path),
                        'scanned_signature' => $this->fileUploadService->getEmployeeDocumentUrl($registration->scanned_signature_path),
                        'passport_photograph' => $this->fileUploadService->getEmployeeDocumentUrl($registration->passport_photograph_path),
                        'nin_document' => $this->fileUploadService->getEmployeeDocumentUrl($registration->nin_document_path),
                    ],
                    // Tracking
                    'consent_given' => $registration->consent_given,
                    'submitted_at' => $registration->created_at?->toIso8601String(),
                    'approved_at' => $registration->approved_at?->toIso8601String(),
                    'rejected_at' => $registration->rejected_at?->toIso8601String(),
                    'company' => $registration->company ? [
                        'id' => $registration->company->id,
                        'name' => $registration->company->name,
                        'email' => $registration->company->email,
                    ] : null,
                    'employee' => $registration->companyEmployee ? [
                        'id' => $registration->companyEmployee->id,
                        'full_name' => $registration->companyEmployee->full_name,
                        'email' => $registration->companyEmployee->email,
                    ] : null,
                    'approved_by' => $registration->approvedBy ? [
                        'id' => $registration->approvedBy->id,
                        'name' => $registration->approvedBy->name,
                    ] : null,
                    'rejected_by' => $registration->rejectedBy ? [
                        'id' => $registration->rejectedBy->id,
                        'name' => $registration->rejectedBy->name,
                    ] : null,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching Employee registration: ' . $e->getMessage(), [
                'registration_id' => $registration->id,
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching the submission.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Update an Employee registration.
     */
    public function update(UpdateEmployeeRegistrationRequest $request, EmployeeRegistration $registration): JsonResponse
    {
        try {
            // Check if rejected
            if ($registration->isRejected()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot update a rejected submission.',
                ], 422);
            }

            $validated = $request->validated();

            // Handle file uploads if present
            if ($request->hasFile('identity_card')) {
                $validated['identity_card_path'] = $this->fileUploadService->uploadDocument(
                    $request->file('identity_card'),
                    'identity_card'
                );
                unset($validated['identity_card']);
            }

            if ($request->hasFile('scanned_signature')) {
                $validated['scanned_signature_path'] = $this->fileUploadService->uploadDocument(
                    $request->file('scanned_signature'),
                    'scanned_signature'
                );
                unset($validated['scanned_signature']);
            }

            if ($request->hasFile('passport_photograph')) {
                $validated['passport_photograph_path'] = $this->fileUploadService->uploadDocument(
                    $request->file('passport_photograph'),
                    'passport_photograph'
                );
                unset($validated['passport_photograph']);
            }

            if ($request->hasFile('nin_document')) {
                $validated['nin_document_path'] = $this->fileUploadService->uploadDocument(
                    $request->file('nin_document'),
                    'nin_document'
                );
                unset($validated['nin_document']);
            }

            $updatedRegistration = $this->registrationService->updateSubmission(
                $registration,
                $validated
            );

            $this->auditService->success(
                AuditLog::ACTION_EMPLOYEE_REGISTRATION_UPDATED,
                AuditLog::ACTOR_ADMIN,
                $request->user()->id,
                $request->user()->email,
                'EmployeeRegistration', $updatedRegistration->id,
                ['name' => $updatedRegistration->first_name . ' ' . $updatedRegistration->last_name, 'fields_updated' => array_keys($validated)],
                $request->ip(),
            );

            return response()->json([
                'success' => true,
                'message' => 'Employee registration updated successfully.',
                'data' => [
                    'id' => $updatedRegistration->id,
                    'first_name' => $updatedRegistration->first_name,
                    'last_name' => $updatedRegistration->last_name,
                    'email_address' => $updatedRegistration->email_address,
                    'phone_number' => $updatedRegistration->phone_number,
                    'status' => $updatedRegistration->status,
                ],
            ]);
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Exception $e) {
            Log::error('Error updating Employee registration: ' . $e->getMessage(), [
                'registration_id' => $registration->id,
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while updating the submission.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Approve an Employee registration.
     * Creates employee and portal user accounts without sending invitation.
     */
    public function approve(EmployeeRegistration $registration, Request $request): JsonResponse
    {
        try {
            // Check if already approved
            if ($registration->isApproved() || $registration->isStatusVerified()) {
                return response()->json([
                    'success' => false,
                    'message' => 'This submission has already been approved.',
                ], 422);
            }

            // Check if already rejected
            if ($registration->isRejected()) {
                return response()->json([
                    'success' => false,
                    'message' => 'This submission has been rejected and cannot be approved.',
                ], 422);
            }

            $updatedRegistration = $this->registrationService->approveSubmission($registration, $request->user()->id);

            $this->auditService->success(
                AuditLog::ACTION_EMPLOYEE_REGISTRATION_APPROVED,
                AuditLog::ACTOR_ADMIN,
                $request->user()->id,
                $request->user()->email,
                'EmployeeRegistration', $updatedRegistration->id,
                ['name' => $updatedRegistration->first_name . ' ' . $updatedRegistration->last_name],
                $request->ip(),
            );

            return response()->json([
                'success' => true,
                'message' => 'Employee registration approved successfully. Account created and visible to company.',
                'data' => [
                    'id' => $updatedRegistration->id,
                    'first_name' => $updatedRegistration->first_name,
                    'last_name' => $updatedRegistration->last_name,
                    'email_address' => $updatedRegistration->email_address,
                    'status' => $updatedRegistration->status,
                    'account_status' => $updatedRegistration->account_status,
                    'company_employee_id' => $updatedRegistration->company_employee_id,
                    'approved_at' => $updatedRegistration->approved_at->toIso8601String(),
                ],
            ]);
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Exception $e) {
            Log::error('Error approving Employee registration: ' . $e->getMessage(), [
                'registration_id' => $registration->id,
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while approving the submission.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Verify an employee registration (mark as verified).
     * This is a dummy implementation for now.
     */
    public function verify(EmployeeRegistration $registration, Request $request): JsonResponse
    {
        try {
            // Check if already verified
            if ($registration->isStatusVerified()) {
                return response()->json([
                    'success' => false,
                    'message' => 'This registration has already been verified.',
                ], 422);
            }

            // Check if not approved yet
            if (!$registration->isApproved()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Only approved registrations can be verified.',
                ], 422);
            }

            $updatedRegistration = $this->registrationService->verifyRegistration($registration, $request->user()->id);

            $this->auditService->success(
                AuditLog::ACTION_EMPLOYEE_REGISTRATION_VERIFIED,
                AuditLog::ACTOR_ADMIN,
                $request->user()->id,
                $request->user()->email,
                'EmployeeRegistration', $updatedRegistration->id,
                ['name' => $updatedRegistration->first_name . ' ' . $updatedRegistration->last_name],
                $request->ip(),
            );

            return response()->json([
                'success' => true,
                'message' => 'Employee registration verified successfully.',
                'data' => [
                    'id' => $updatedRegistration->id,
                    'first_name' => $updatedRegistration->first_name,
                    'last_name' => $updatedRegistration->last_name,
                    'email_address' => $updatedRegistration->email_address,
                    'status' => $updatedRegistration->status,
                ],
            ]);
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Exception $e) {
            Log::error('Error verifying Employee registration: ' . $e->getMessage(), [
                'registration_id' => $registration->id,
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while verifying the registration.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Send invitation to Employee registration.
     * Approves the registration, creates employee account and portal user, then sends invitation email.
     */
    public function sendInvitation(EmployeeRegistration $registration, SendInvitationRequest $request): JsonResponse
    {
        try {
            // Check if already rejected
            if ($registration->isRejected()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot send invitation to a rejected registration.',
                ], 422);
            }

            // Check if already invited or active
            if ($registration->isAccountInvited() || $registration->isAccountActive()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invitation has already been sent or account is already active.',
                ], 422);
            }

            $validated = $request->validated();
            $email = $validated['email'] ?? null;

            $employee = $this->registrationService->sendInvitation($registration, $email, $request->user()->id);

            $this->auditService->success(
                AuditLog::ACTION_EMPLOYEE_INVITATION_SENT,
                AuditLog::ACTOR_ADMIN,
                $request->user()->id,
                $request->user()->email,
                'EmployeeRegistration', $registration->id,
                ['employee_name' => $employee->full_name, 'invited_email' => $employee->email],
                $request->ip(),
            );

            return response()->json([
                'success' => true,
                'message' => 'Registration approved and invitation sent successfully. Employee account created and invitation email sent.',
                'data' => [
                    'submission_id' => $registration->fresh()->id,
                    'employee_id' => $employee->id,
                    'employee_name' => $employee->full_name,
                    'employee_email' => $employee->email,
                    'status' => $registration->fresh()->status,
                    'account_status' => $registration->fresh()->account_status,
                ],
            ]);
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Exception $e) {
            Log::error('Error sending Employee registration invitation: ' . $e->getMessage(), [
                'registration_id' => $registration->id,
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while sending the invitation.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Reject an Employee registration.
     */
    public function reject(EmployeeRegistration $registration, Request $request): JsonResponse
    {
        try {
            // Validate rejection reason
            $validated = $request->validate([
                'rejection_reason' => ['nullable', 'string', 'max:1000'],
            ]);

            // Check if already approved
            if ($registration->isApproved()) {
                return response()->json([
                    'success' => false,
                    'message' => 'This submission has already been approved and cannot be rejected.',
                ], 422);
            }

            // Check if already rejected
            if ($registration->isRejected()) {
                return response()->json([
                    'success' => false,
                    'message' => 'This submission has already been rejected.',
                ], 422);
            }

            $registration = $this->registrationService->rejectSubmission(
                $registration,
                $request->user()->id,
                $validated['rejection_reason'] ?? null
            );

            $this->auditService->success(
                AuditLog::ACTION_EMPLOYEE_REGISTRATION_REJECTED,
                AuditLog::ACTOR_ADMIN,
                $request->user()->id,
                $request->user()->email,
                'EmployeeRegistration', $registration->id,
                ['name' => $registration->first_name . ' ' . $registration->last_name, 'reason' => $registration->rejection_reason],
                $request->ip(),
            );

            return response()->json([
                'success' => true,
                'message' => 'Employee registration rejected successfully. Rejection email sent.',
                'data' => [
                    'submission_id' => $registration->id,
                    'employee_name' => $registration->first_name . ' ' . $registration->last_name,
                    'rejection_reason' => $registration->rejection_reason,
                    'rejected_at' => $registration->rejected_at->toIso8601String(),
                ],
            ]);
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Exception $e) {
            Log::error('Error rejecting Employee registration: ' . $e->getMessage(), [
                'registration_id' => $registration->id,
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while rejecting the submission.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Export Employee registrations to CSV.
     */
    public function exportCsv(Request $request)
    {
        $filters = [];
        if ($request->has('status'))          $filters['status']          = $request->input('status');
        if ($request->has('submission_type')) $filters['submission_type'] = $request->input('submission_type');
        if ($request->has('company_id'))      $filters['company_id']      = $request->input('company_id');
        if ($request->has('from_date'))       $filters['from_date']       = $request->input('from_date');
        if ($request->has('to_date'))         $filters['to_date']         = $request->input('to_date');

        $submissions = $this->registrationService->getSubmissionsForExport($filters);

        $filename = 'employee-registrations-' . now()->format('Y-m-d') . '.csv';

        $headers = [
            'Content-Type'        => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ];

        $columns = ['ID', 'Company', 'First Name', 'Last Name', 'Email', 'Phone', 'Country', 'State', 'City', 'Submission Type', 'Status', 'Account Status', 'Verification Status', 'Submitted At', 'Approved At', 'Rejected At'];

        return response()->streamDownload(function () use ($submissions, $columns) {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, $columns);

            foreach ($submissions as $row) {
                fputcsv($handle, [
                    $row->id,
                    $row->company?->name,
                    $row->first_name,
                    $row->last_name,
                    $row->email_address,
                    $row->phone_number,
                    $row->country,
                    $row->state,
                    $row->city,
                    $row->submission_type,
                    $row->status,
                    $row->account_status,
                    $row->verification_status,
                    $row->created_at?->toIso8601String(),
                    $row->approved_at?->toIso8601String(),
                    $row->rejected_at?->toIso8601String(),
                ]);
            }

            fclose($handle);
        }, $filename, $headers);
    }

    /**
     * Bulk upload employees via CSV.
     */
    public function bulkUpload(BulkUploadEmployeeRegistrationRequest $request): JsonResponse
    {
        try {
            $csvFile = $request->file('csv_file');
            $sendInvitations = $request->input('send_invitations', false);

            // Store CSV temporarily
            $csvPath = $csvFile->getRealPath();
            $originalFilename = $csvFile->getClientOriginalName();

            // Process CSV
            $results = $this->bulkUploadService->processCsvUpload($csvPath, $sendInvitations, $originalFilename);

            $this->auditService->success(
                AuditLog::ACTION_EMPLOYEE_BULK_UPLOAD,
                AuditLog::ACTOR_ADMIN,
                $request->user()->id,
                $request->user()->email,
                null, null,
                ['total' => $results['total_rows'], 'success' => $results['successful_count'], 'failed' => $results['failed_count'], 'filename' => $originalFilename],
                $request->ip(),
            );

            $statusCode = $results['failed_count'] > 0 ? 207 : 201; // 207 Multi-Status if there are failures

            return response()->json([
                'success' => true,
                'message' => sprintf(
                    'Bulk upload completed. %d successful, %d failed out of %d total rows.',
                    $results['successful_count'],
                    $results['failed_count'],
                    $results['total_rows']
                ),
                'data' => [
                    'summary' => [
                        'total_rows' => $results['total_rows'],
                        'successful_count' => $results['successful_count'],
                        'failed_count' => $results['failed_count'],
                    ],
                    'successful' => $results['successful'],
                    'failed' => $results['failed'],
                ],
            ], $statusCode);
        } catch (\Exception $e) {
            Log::error('Error processing bulk CSV upload: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while processing the CSV file.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Run AML/PEP screening for an employee registration.
     */
    public function amlScreen(EmployeeRegistration $registration, Request $request): JsonResponse
    {
        try {
            $screening = $this->amlScreeningService->screenEmployeeRegistration(
                $registration,
                $request->user()->id
            );

            return response()->json([
                'success' => true,
                'message' => 'AML screening completed.',
                'data'    => $this->formatScreeningResult($screening),
            ]);
        } catch (\RuntimeException $e) {
            $serviceDown = $e->serviceUnavailable ?? false;
            return response()->json(array_filter([
                'success'      => false,
                'service_down' => $serviceDown ?: null,
                'message'      => $e->getMessage(),
            ]), $serviceDown ? 503 : 422);
        } catch (\Exception $e) {
            Log::error('Error running AML screening for employee registration: ' . $e->getMessage(), [
                'registration_id' => $registration->id,
                'exception'       => $e,
            ]);
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while running AML screening.',
                'error'   => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    private function formatScreeningResult(\App\Models\AmlScreeningResult $screening): array
    {
        return [
            'id'             => $screening->id,
            'risk_level'     => $screening->risk_level,
            'match_status'   => $screening->match_status,
            'total_results'  => $screening->total_results,
            'total_articles' => $screening->total_articles,
            'results'        => $screening->results,
            'screened_at'    => $screening->screened_at->toIso8601String(),
        ];
    }
}
