<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class MatchGame extends Model
{
    use HasFactory;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'matches';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'competition_id',
        'scheduling_mode_id',
        'home_team_id',
        'away_team_id',
        'field_id',
        'start_time',
        'end_time',
        'home_team_score',
        'away_team_score',
        'status',
        'round',
        'group',
        'match_number',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'home_team_score' => 'integer',
        'away_team_score' => 'integer',
    ];

    /**
     * Get the competition that the match belongs to.
     */
    public function competition(): BelongsTo
    {
        return $this->belongsTo(Competition::class);
    }

    /**
     * Get the scheduling mode that this match is part of.
     */
    public function schedulingMode(): BelongsTo
    {
        return $this->belongsTo(SchedulingMode::class);
    }

    /**
     * Get the home team.
     */
    public function homeTeam(): BelongsTo
    {
        return $this->belongsTo(Team::class, 'home_team_id');
    }

    /**
     * Get the away team.
     */
    public function awayTeam(): BelongsTo
    {
        return $this->belongsTo(Team::class, 'away_team_id');
    }

    /**
     * Get the field where the match is played.
     */
    public function field(): BelongsTo
    {
        return $this->belongsTo(Field::class);
    }

    /**
     * Determine if this match is during a break period.
     *
     * @return bool
     */
    public function hasBankPeriod()
    {
        return BreakPeriod::where('competition_id', $this->competition_id)
            ->where('start_time', '<=', $this->start_time)
            ->where('end_time', '>=', $this->end_time)
            ->exists();
    }
}
