<?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;

class CareUnit extends Model
{
    use BelongsToOwner, SoftDeletes;

    protected $table = 'care_care_units';

    protected $fillable = [
        'owner_ref',
        'organization_id',
        'department_id',
        'name',
        'code',
        'kind',
        'is_active',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

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

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class, 'department_id');
    }

    public function beds(): HasMany
    {
        return $this->hasMany(Bed::class, 'care_unit_id')->orderBy('sort_order')->orderBy('label');
    }

    public function assignments(): HasMany
    {
        return $this->hasMany(StaffAssignment::class, 'care_unit_id');
    }

    public function visits(): HasMany
    {
        return $this->hasMany(Visit::class, 'care_unit_id');
    }

    public function activeStays(): HasMany
    {
        return $this->hasMany(BedStay::class, 'care_unit_id')->where('status', BedStay::STATUS_ACTIVE);
    }

    public function supportsBeds(): bool
    {
        return $this->kind === 'inpatient';
    }

    public function labelForSelect(): string
    {
        $dept = $this->relationLoaded('department')
            ? $this->department
            : $this->department()->first();

        $kindLabel = config('care.care_unit_kinds.'.$this->kind, $this->kind);
        $base = $this->name.($kindLabel ? ' ('.$kindLabel.')' : '');

        if ($dept?->name) {
            return $dept->name.' — '.$base;
        }

        return $base;
    }
}
