<?php

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

use App\Domain\Recruitment\Enums\JobDemandStatus;
use App\Domain\Recruitment\Models\JobDemand;
use App\Domain\Recruitment\Services\JobDemandService;
use App\Http\Controllers\Controller;
use App\Http\Requests\Recruitment\ChangeJobDemandStatusRequest;
use App\Http\Resources\JobDemandResource;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

class JobDemandStatusController extends Controller
{
    public function __construct(private readonly JobDemandService $demands) {}

    public function __invoke(ChangeJobDemandStatusRequest $request, JobDemand $jobDemand): JsonResponse
    {
        $target = $request->status();

        $ability = match (true) {
            $target->requiresApproval() => 'approve',
            in_array($target, [JobDemandStatus::Closed, JobDemandStatus::Cancelled], true) => 'close',
            default => 'update',
        };

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

        $demand = $this->demands->changeStatus($jobDemand, $target, $request->input('reason'), $request->user());

        return ApiResponse::success(
            new JobDemandResource($demand->load(['employer', 'branch:id,uuid,name'])),
            "Job demand marked {$target->label()}.",
        );
    }
}
