<?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 odds_versions} */
final class OddsVersion 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 (OddsVersion $m): void {
            if ($m->status === null || $m->status === '') {
                $m->status = ConfigVersionStatus::Draft->value;
            }
        });
    }

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

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

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