<?php

namespace App\Domain\Processing\Models;

use App\Domain\Applicants\Models\Applicant;
use App\Domain\Identity\Models\User;
use App\Domain\Processing\Enums\MedicalStatus;
use App\Support\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class MedicalRecord extends Model
{
    use HasFactory, HasUuid, SoftDeletes;

    protected $guarded = ['id', 'uuid'];

    protected function casts(): array
    {
        return [
            'status' => MedicalStatus::class,
            'appointment_date' => 'date',
            'result_date' => 'date',
            'expiry_date' => 'date',
            'is_current' => 'boolean',
            'attempt' => 'integer',
        ];
    }

    public function applicant(): BelongsTo
    {
        return $this->belongsTo(Applicant::class);
    }

    public function recordedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'recorded_by');
    }

    public function scopeCurrent(Builder $query): Builder
    {
        return $query->where('is_current', true);
    }

    public function hasExpired(): bool
    {
        return $this->expiry_date !== null && $this->expiry_date->isPast();
    }

    /**
     * An expired certificate does not clear anyone, whatever it once said —
     * the same rule the documents module applies to verification.
     */
    public function effectiveStatus(): MedicalStatus
    {
        if ($this->hasExpired() && $this->status === MedicalStatus::Fit) {
            return MedicalStatus::Expired;
        }

        return $this->status;
    }

    public function clearsForDeployment(): bool
    {
        return $this->effectiveStatus()->isCleared();
    }
}
