<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;

class ClcAuthorizedVet extends Model
{
    protected $table = 'clc_authorized_vets';
    protected $guarded = ['id'];

    protected $casts = [
        'schedules'   => 'array',
        'valid_until' => 'date',
    ];

    public function doctor()
    {
        return $this->belongsTo(ClcDoctor::class, 'doctor_id');
    }

    /** Permit is "currently valid" — true when no expiry, OR expiry in the future. */
    public function getIsValidAttribute(): bool
    {
        if (!$this->valid_until) return true;
        return $this->valid_until->isFuture() || $this->valid_until->isToday();
    }

    public function getIsExpiringAttribute(): bool
    {
        if (!$this->valid_until) return false;
        return $this->valid_until->isFuture() && $this->valid_until->diffInDays(now()) <= 30;
    }

    /**
     * Is the given doctor authorised to dispense a given schedule right now?
     * Returns one of: 'ok' | 'no_permit' | 'wrong_schedule' | 'expired'.
     */
    public static function checkAuthorization(int $businessId, ?int $doctorId, ?string $schedule): string
    {
        if (!$doctorId || !$schedule) return 'no_permit';
        $row = static::where('business_id', $businessId)
            ->where('doctor_id', $doctorId)
            ->first();
        if (!$row) return 'no_permit';
        $schedules = $row->schedules ?? [];
        if (!in_array($schedule, $schedules, true)) return 'wrong_schedule';
        if ($row->valid_until && $row->valid_until->isPast()) return 'expired';
        return 'ok';
    }
}
