<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\Models\RecruitmentApplication;
use App\Modules\HR\Recruitment\Repositories\CareerPortalVacancyRepository;
use App\Modules\HR\Recruitment\Support\OfferLetterStatus;
use Illuminate\Validation\ValidationException;

class CareerPortalTrackingService
{
    public function __construct(
        private readonly CareerPortalVacancyRepository $repository,
    ) {}

    public function findByToken(int $tenantId, string $token): RecruitmentApplication
    {
        $app = $this->repository->findByTrackingToken($tenantId, $token);
        if ($app === null) {
            throw ValidationException::withMessages([
                'token' => __('recruitment.career_portal.errors.tracking_not_found'),
            ]);
        }

        return $app;
    }

    /** @return list<\App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter> */
    public function visibleOffers(RecruitmentApplication $application): array
    {
        $visible = [
            OfferLetterStatus::SENT,
            OfferLetterStatus::ACCEPTED,
            OfferLetterStatus::HIRED,
            OfferLetterStatus::REJECTED,
            OfferLetterStatus::EXPIRED,
            OfferLetterStatus::WITHDRAWN,
        ];

        return $application->offerLetters
            ->filter(fn ($o) => in_array($o->status, $visible, true))
            ->values()
            ->all();
    }
}
