<?php

namespace App\Models;

use App\Enums\MatchOutcome;
use App\Enums\MatchStatus;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[Fillable([
    'home_team_id',
    'away_team_id',
    'stage',
    'venue',
    'starts_at',
    'picks_lock_at',
    'status',
    'home_score',
    'away_score',
    'result',
    'result_declared_at',
])]
class Fixture extends Model
{
    protected $table = 'matches';

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'starts_at' => 'datetime',
            'picks_lock_at' => 'datetime',
            'status' => MatchStatus::class,
            'home_score' => 'integer',
            'away_score' => 'integer',
            'result' => MatchOutcome::class,
            'result_declared_at' => 'datetime',
        ];
    }

    public function homeTeam(): BelongsTo
    {
        return $this->belongsTo(Team::class, 'home_team_id');
    }

    public function awayTeam(): BelongsTo
    {
        return $this->belongsTo(Team::class, 'away_team_id');
    }

    public function picks(): HasMany
    {
        return $this->hasMany(Pick::class, 'match_id');
    }

    public function isOpenForPicks(): bool
    {
        $lockAt = $this->picks_lock_at ?? $this->starts_at;

        return $this->status === MatchStatus::Scheduled
            && $lockAt !== null
            && $lockAt->isFuture();
    }
}
