<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter;
use App\Modules\HR\Recruitment\Support\OfferLetterStatus;
use Illuminate\Validation\ValidationException;

class RecruitmentOfferLetterExpiryService
{
    public function assertReadyToSend(RecruitmentOfferLetter $row): void
    {
        if ($row->expires_at === null || $row->acceptance_deadline_at === null) {
            throw ValidationException::withMessages([
                'expires_at' => __('recruitment.offer_letters.errors.expiry_required_to_send'),
            ]);
        }
        if ($row->acceptance_deadline_at->isPast() || $row->expires_at->isPast()) {
            throw ValidationException::withMessages([
                'acceptance_deadline_at' => __('recruitment.offer_letters.errors.deadline_in_past'),
            ]);
        }
    }

    public function assertNotPastDeadline(RecruitmentOfferLetter $row): void
    {
        if ($row->acceptance_deadline_at !== null && $row->acceptance_deadline_at->isPast()) {
            throw ValidationException::withMessages([
                'acceptance_deadline_at' => __('recruitment.offer_letters.errors.acceptance_deadline_passed'),
            ]);
        }
        if ($row->expires_at !== null && $row->expires_at->isPast()) {
            throw ValidationException::withMessages([
                'expires_at' => __('recruitment.offer_letters.errors.offer_expired'),
            ]);
        }
    }

    public function expireIfPastDeadline(RecruitmentOfferLetter $row, RecruitmentOfferLetterWorkflowService $workflow, int $userId): RecruitmentOfferLetter
    {
        if ($row->status !== OfferLetterStatus::SENT) {
            return $row;
        }
        $past = ($row->acceptance_deadline_at !== null && $row->acceptance_deadline_at->isPast())
            || ($row->expires_at !== null && $row->expires_at->isPast());
        if (! $past) {
            return $row;
        }

        return $workflow->expire($row, $userId, __('recruitment.offer_letters.notes.auto_expired'));
    }
}
