<?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\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Visit extends Model
{
    use BelongsToOwner, SoftDeletes;

    public const STATUS_OPEN = 'open';

    public const STATUS_IN_PROGRESS = 'in_progress';

    public const STATUS_COMPLETED = 'completed';

    protected $table = 'care_visits';

    protected $fillable = [
        'uuid', 'owner_ref', 'organization_id', 'branch_id', 'patient_id',
        'care_unit_id', 'bed_id', 'placed_at', 'placed_by',
        'status', 'specialty_stage', 'checked_in_at', 'completed_at', 'checked_in_by',
    ];

    protected function casts(): array
    {
        return [
            'checked_in_at' => 'datetime',
            'completed_at' => 'datetime',
            'placed_at' => 'datetime',
        ];
    }

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

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

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

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }

    public function organization(): BelongsTo
    {
        return $this->belongsTo(Organization::class, 'organization_id');
    }

    public function careUnit(): BelongsTo
    {
        return $this->belongsTo(CareUnit::class, 'care_unit_id');
    }

    public function bed(): BelongsTo
    {
        return $this->belongsTo(Bed::class, 'bed_id');
    }

    public function bedStays(): HasMany
    {
        return $this->hasMany(BedStay::class, 'visit_id');
    }

    public function activeBedStay(): HasOne
    {
        return $this->hasOne(BedStay::class, 'visit_id')
            ->ofMany(
                ['id' => 'max'],
                fn ($query) => $query->where('status', BedStay::STATUS_ACTIVE),
            );
    }

    public function appointment(): HasOne
    {
        return $this->hasOne(Appointment::class, 'visit_id');
    }

    public function consultations(): HasMany
    {
        return $this->hasMany(Consultation::class, 'visit_id');
    }

    public function assessments(): HasMany
    {
        return $this->hasMany(Assessment::class, 'visit_id');
    }

    public function bill(): HasOne
    {
        return $this->hasOne(Bill::class, 'visit_id');
    }

    public function bills(): HasMany
    {
        return $this->hasMany(Bill::class, 'visit_id');
    }

    public function stageAdvances(): HasMany
    {
        return $this->hasMany(VisitStageAdvance::class, 'visit_id');
    }

    /**
     * Active or blocked advance for the visit's current workflow stage.
     * Prefer this for eager-loaded queue board filtering (avoids N+1 currentAdvance queries).
     */
    public function currentStageAdvance(): HasOne
    {
        return $this->hasOne(VisitStageAdvance::class, 'visit_id')
            ->ofMany(
                ['id' => 'max'],
                fn ($query) => $query->whereIn('status', [
                    VisitStageAdvance::STATUS_ACTIVE,
                    VisitStageAdvance::STATUS_BLOCKED,
                ]),
            );
    }

    public function financialObligations(): HasMany
    {
        return $this->hasMany(FinancialObligation::class, 'visit_id');
    }
}
