<?php

namespace App\Services\Recruitment;

use App\Models\Applicant;

class ReferralDuplicateService
{
    public function isDuplicate(int $companyId, int $jobPostingId, ?string $email, ?int $ignoreApplicantId = null): bool
    {
        if (! config('recruitment.block_duplicate_email_per_job', true)) {
            return false;
        }

        $email = trim((string) $email);
        if ($email === '') {
            return false;
        }

        return Applicant::query()
            ->where('company_id', $companyId)
            ->where('job_posting_id', $jobPostingId)
            ->whereRaw('LOWER(email) = ?', [strtolower($email)])
            ->when($ignoreApplicantId, fn ($q) => $q->where('id', '!=', $ignoreApplicantId))
            ->whereNotIn('stage', ['rejected'])
            ->exists();
    }
}
