<?php

namespace App\Models;

use App\Lottery\ConfigVersionStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/** {@see risk_cap_versions} */
final class RiskCapVersion extends Model
{
    protected $fillable = [
        'version_no',
        'status',
        'effective_at',
        'updated_by',
        'reason',
    ];

    protected function casts(): array
    {
        return [
            'version_no' => 'integer',
            'effective_at' => 'datetime',
            'updated_by' => 'integer',
        ];
    }

    protected static function booted(): void
    {
        self::saving(function (RiskCapVersion $m): void {
            if ($m->status === null || $m->status === '') {
                $m->status = ConfigVersionStatus::Draft->value;
            }
        });
    }

    /** @return BelongsTo<AdminUser, RiskCapVersion> */
    public function updatedByAdmin(): BelongsTo
    {
        return $this->belongsTo(AdminUser::class, 'updated_by');
    }

    /** @return HasMany<RiskCapItem, RiskCapVersion> */
    public function items(): HasMany
    {
        return $this->hasMany(RiskCapItem::class, 'version_id');
    }

    public function isDraft(): bool
    {
        return $this->status === ConfigVersionStatus::Draft->value;
    }
}
