<?php

namespace App\Models;

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

class FinancialObligation extends Model
{
    use BelongsToOwner, SoftDeletes;

    public const STATUS_PENDING = 'pending';

    public const STATUS_AUTHORIZED = 'authorized';

    public const STATUS_PAID = 'paid';

    public const STATUS_WAIVED = 'waived';

    public const STATUS_DEFERRED = 'deferred';

    public const STATUS_VOID = 'void';

    /** Statuses that satisfy a financial gate. */
    public const CLEARED_STATUSES = [
        self::STATUS_AUTHORIZED,
        self::STATUS_PAID,
        self::STATUS_WAIVED,
        self::STATUS_DEFERRED,
    ];

    protected $table = 'care_financial_obligations';

    protected $fillable = [
        'uuid', 'owner_ref', 'organization_id', 'branch_id', 'visit_id', 'patient_id',
        'workflow_stage_id', 'bill_id', 'stage_code', 'charge_code', 'label',
        'amount_minor', 'status', 'clearance_method', 'payment_mode',
        'external_reference', 'cleared_by', 'cleared_at', 'meta',
    ];

    protected function casts(): array
    {
        return [
            'amount_minor' => 'integer',
            'cleared_at' => 'datetime',
            'meta' => 'array',
        ];
    }

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

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

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

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

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

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

    public function stage(): BelongsTo
    {
        return $this->belongsTo(WorkflowStage::class, 'workflow_stage_id');
    }

    public function bill(): BelongsTo
    {
        return $this->belongsTo(Bill::class, 'bill_id');
    }

    public function isCleared(): bool
    {
        return in_array($this->status, self::CLEARED_STATUSES, true);
    }
}
