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

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

    /** @return HasMany<PlayConfigItem, PlayConfigVersion> */
    public function items(): HasMany
    {
        return $this->hasMany(PlayConfigItem::class, 'version_id')
            ->orderBy('display_order')
            ->orderBy('play_code');
    }

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