<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Patient extends Model
{
    protected $fillable = [
        'client_id',
        'clinical_code',
        'name',
        'species',
        'breed',
        'sex',
        'birth_date',
        'color',
        'microchip',
        'current_weight_kg',
        'notes',
        'allergies',
        'sterilized',
        'photo_path',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'birth_date' => 'date',
            'is_active' => 'boolean',
            'sterilized' => 'boolean',
            'current_weight_kg' => 'decimal:3',
        ];
    }

    protected static function booted(): void
    {
        static::created(function (Patient $patient): void {
            if (filled($patient->clinical_code)) {
                return;
            }
            $patient->forceFill([
                'clinical_code' => 'PAC-'.str_pad((string) $patient->id, 6, '0', STR_PAD_LEFT),
            ])->saveQuietly();
        });
    }

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

    public function medicalRecords(): HasMany
    {
        return $this->hasMany(MedicalRecord::class)->orderByDesc('recorded_at');
    }

    public function productReservations(): HasMany
    {
        return $this->hasMany(ProductReservation::class)->orderByDesc('created_at');
    }

    public function appointments(): HasMany
    {
        return $this->hasMany(Appointment::class)->orderBy('starts_at');
    }

    public function mediaFiles(): HasMany
    {
        return $this->hasMany(PatientMedia::class)->orderByDesc('created_at');
    }
}
