<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Http\Requests\AmlScreenRequest;
use App\Services\AmlScreeningApiService;
use Illuminate\Http\JsonResponse;

class AmlScreeningController extends Controller
{
    public function __construct(
        private readonly AmlScreeningApiService $amlService,
    ) {}

    /**
     * Run an AML/PEP screening check.
     * Used for both public and admin routes — auth enforced at route level.
     * Nothing is stored — caller receives the full Dojah response.
     */
    public function screen(AmlScreenRequest $request): JsonResponse
    {
        $validated = $request->validated();
        $schema    = $validated['schema'] ?? 'individual';

        $result = $schema === 'organization'
            ? $this->amlService->screenOrganization(
                names: $validated['names'],
                registrationNumber: $validated['registration_number'] ?? null,
                country: $validated['country'] ?? null,
            )
            : $this->amlService->screenIndividual(
                names: $validated['names'],
                dateOfBirth: $validated['date_of_birth'] ?? null,
                nationality: $validated['nationality'] ?? null,
                gender: $validated['gender'] ?? null,
            );

        if (! $result['success']) {
            $serviceDown = $result['service_unavailable'] ?? false;
            return response()->json(array_filter([
                'success'      => false,
                'service_down' => $serviceDown ?: null,
                'message'      => $result['message'] ?? 'AML screening failed.',
            ]), $serviceDown ? 503 : 422);
        }

        return response()->json([
            'success' => true,
            'message' => 'AML screening completed.',
            'data'    => [
                'risk_level'     => $result['risk_level'],
                'match_status'   => $result['match_status'],
                'total_results'  => $result['total_results'],
                'total_articles' => $result['total_articles'],
                'results'        => $result['results'],
            ],
        ]);
    }
}
