<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Prescription extends Model
{
    use BelongsToOwner, SoftDeletes;

    public const STATUS_DRAFT = 'draft';

    public const STATUS_ACTIVE = 'active';

    public const STATUS_DISPENSED = 'dispensed';

    public const STATUS_CANCELLED = 'cancelled';

    protected $table = 'care_prescriptions';

    protected $fillable = [
        'uuid', 'queue_ticket_uuid', 'queue_ticket_number', 'queue_ticket_status',
        'queue_service_point_uuid', 'queue_destination', 'queue_staff_display_name', 'queue_routing_status',
        'owner_ref', 'organization_id', 'visit_id', 'consultation_id',
        'patient_id', 'practitioner_id', 'status', 'notes',
        'prescribed_by', 'dispensed_by', 'dispensed_at',
    ];

    protected function casts(): array
    {
        return ['dispensed_at' => 'datetime'];
    }

    protected static function booted(): void
    {
        static::creating(function (Prescription $prescription) {
            if (! $prescription->uuid) {
                $prescription->uuid = (string) Str::uuid();
            }
        });
    }

    public function getRouteKeyName(): string
    {
        return 'uuid';
    }

    public function patient(): BelongsTo
    {
        return $this->belongsTo(Patient::class, 'patient_id');
    }

    public function visit(): BelongsTo
    {
        return $this->belongsTo(Visit::class, 'visit_id');
    }

    public function consultation(): BelongsTo
    {
        return $this->belongsTo(Consultation::class, 'consultation_id');
    }

    public function practitioner(): BelongsTo
    {
        return $this->belongsTo(Practitioner::class, 'practitioner_id');
    }

    public function items(): HasMany
    {
        return $this->hasMany(PrescriptionItem::class, 'prescription_id')->orderBy('sort_order');
    }
}
