<?php

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

use App\Domain\Agents\Models\Agent;
use App\Domain\Applicants\Models\Applicant;
use App\Domain\Applicants\Services\ApplicantAssignmentService;
use App\Domain\Identity\Models\User;
use App\Http\Controllers\Controller;
use App\Http\Resources\ApplicantResource;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ApplicantAssignmentController extends Controller
{
    public function __construct(private readonly ApplicantAssignmentService $assignments) {}

    public function assignAgent(Request $request, Applicant $applicant): JsonResponse
    {
        $this->authorize('assignAgent', $applicant);

        $validated = $request->validate([
            // Null clears the assignment.
            'agent_id' => ['nullable', 'uuid', Rule::exists('agents', 'uuid')->whereNull('deleted_at')],
            'reason' => ['nullable', 'string', 'max:500'],
        ]);

        $agent = isset($validated['agent_id'])
            ? Agent::where('uuid', $validated['agent_id'])->firstOrFail()
            : null;

        $applicant = $this->assignments->assignAgent(
            $applicant,
            $agent,
            $request->user(),
            $validated['reason'] ?? null,
        );

        return ApiResponse::success(
            new ApplicantResource($applicant->fresh()->load(['agent:id,uuid,name,agent_code'])),
            $agent === null ? 'Agent removed.' : "Assigned to {$agent->name}.",
        );
    }

    public function assignStaff(Request $request, Applicant $applicant): JsonResponse
    {
        $this->authorize('assignStaff', $applicant);

        $validated = $request->validate([
            'assigned_to' => ['nullable', 'uuid', Rule::exists('users', 'uuid')->whereNull('deleted_at')],
            'reason' => ['nullable', 'string', 'max:500'],
        ]);

        $staff = isset($validated['assigned_to'])
            ? User::where('uuid', $validated['assigned_to'])->firstOrFail()
            : null;

        $applicant = $this->assignments->assignStaff(
            $applicant,
            $staff,
            $request->user(),
            $validated['reason'] ?? null,
        );

        return ApiResponse::success(
            new ApplicantResource($applicant->fresh()->load(['assignedStaff:id,uuid,name'])),
            $staff === null ? 'Staff owner removed.' : "Assigned to {$staff->name}.",
        );
    }
}
