<?php

namespace App\Http\Controllers\Api\V1\Applicants;

use App\Domain\Applicants\Models\Applicant;
use App\Domain\Applicants\Services\ApplicantService;
use App\Http\Controllers\Controller;
use App\Http\Requests\Applicants\MergeApplicantRequest;
use App\Http\Resources\ApplicantResource;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

/**
 * Folds the routed applicant into the survivor named in the payload (§9.2).
 */
class ApplicantMergeController extends Controller
{
    public function __construct(private readonly ApplicantService $applicants) {}

    public function __invoke(MergeApplicantRequest $request, Applicant $applicant): JsonResponse
    {
        $this->authorize('merge', $applicant);

        $survivor = Applicant::where('uuid', $request->string('survivor_id'))->firstOrFail();

        // The survivor must also be within the caller's reach.
        $this->authorize('merge', $survivor);

        $survivor = $this->applicants->merge($applicant, $survivor, $request->user());

        return ApiResponse::success(
            new ApplicantResource($survivor->load(['agent:id,uuid,name,agent_code', 'branch:id,uuid,name'])),
            "Applicant merged into {$survivor->reference_no}.",
        );
    }
}
