<?php

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

use App\Domain\Agents\Enums\AgentStatus;
use App\Domain\Agents\Models\Agent;
use App\Domain\Agents\Services\AgentService;
use App\Http\Controllers\Controller;
use App\Http\Requests\Agents\ChangeAgentStatusRequest;
use App\Http\Resources\AgentResource;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

/**
 * Status changes are a separate endpoint because approving, suspending and
 * blacklisting are distinct permissions from editing a profile (§12).
 */
class AgentStatusController extends Controller
{
    public function __construct(private readonly AgentService $agents) {}

    public function __invoke(ChangeAgentStatusRequest $request, Agent $agent): JsonResponse
    {
        $target = $request->status();

        $ability = match ($target) {
            AgentStatus::Active => 'approve',
            AgentStatus::Suspended, AgentStatus::Terminated, AgentStatus::Blacklisted => 'suspend',
            default => 'update',
        };

        $this->authorize($ability, $agent);

        $agent = $this->agents->changeStatus($agent, $target, $request->input('reason'), $request->user());

        return ApiResponse::success(
            new AgentResource($agent->load(['branch:id,uuid,name', 'statusHistories.changedBy:id,name'])),
            "Agent marked {$target->label()}.",
        );
    }
}
