<?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\Support\Str;

class WorkflowStage extends Model
{
    use BelongsToOwner;

    public const TIMING_BEFORE = 'before';

    public const TIMING_AFTER = 'after';

    public const TIMING_NONE = 'none';

    protected $table = 'care_workflow_stages';

    protected $fillable = [
        'uuid', 'owner_ref', 'workflow_id', 'code', 'name', 'type',
        'queue_context', 'department_type', 'sort_order',
        'requires_payment', 'payment_timing', 'payment_modes',
        'insurance_eligible', 'credit_allowed', 'allow_override',
        'charge_code', 'charge_label', 'default_amount_minor',
        'default_next', 'can_return', 'can_skip', 'optional', 'creates_child', 'meta',
    ];

    protected function casts(): array
    {
        return [
            'sort_order' => 'integer',
            'requires_payment' => 'boolean',
            'payment_modes' => 'array',
            'insurance_eligible' => 'boolean',
            'credit_allowed' => 'boolean',
            'allow_override' => 'boolean',
            'default_amount_minor' => 'integer',
            'can_return' => 'boolean',
            'can_skip' => 'boolean',
            'optional' => 'boolean',
            'creates_child' => 'boolean',
            'meta' => 'array',
        ];
    }

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

    public function workflow(): BelongsTo
    {
        return $this->belongsTo(FacilityWorkflow::class, 'workflow_id');
    }

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

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

    /** Whether entering this stage's service queue is gated on a cleared obligation. */
    public function gatesBeforeService(): bool
    {
        return $this->requires_payment && $this->payment_timing === self::TIMING_BEFORE;
    }

    public function collectsAfterService(): bool
    {
        return $this->requires_payment && $this->payment_timing === self::TIMING_AFTER;
    }
}
