<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\Repositories\RecruitmentVacancyRepository;
use App\Modules\HR\Recruitment\Support\VacancyStatus;

class HiringVacancyFulfillmentService
{
    public function __construct(
        private readonly RecruitmentVacancyRepository $vacancies,
    ) {}

    public function recordHire(int $tenantId, int $vacancyId): void
    {
        $vacancy = $this->vacancies->lockForTenant($tenantId, $vacancyId);
        abort_if($vacancy === null, 404);

        $filled = ((int) $vacancy->filled_positions) + 1;
        $payload = ['filled_positions' => $filled];
        if ($filled >= (int) $vacancy->openings && $vacancy->status === VacancyStatus::OPEN) {
            $payload['status'] = VacancyStatus::CLOSED;
        }
        $this->vacancies->update($vacancy, $payload);
    }
}
