<?php

namespace App\Models;

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

class GameMatch extends Model
{
    use HasFactory;

    protected $table = 'matches';

    protected $fillable = [
        'host_id', 'guest_id', 'winner_id', 'season_id',
        'score_host', 'score_guest',
        'submitted_host_score_host', 'submitted_host_score_guest',
        'submitted_guest_score_host', 'submitted_guest_score_guest',
        'elo_change_host', 'elo_change_guest',
        'discord_channel_id', 'discord_voice_id',
        'status', 'admin_note',
    ];

    protected $casts = [
        'score_host'       => 'integer',
        'score_guest'      => 'integer',
        'elo_change_host'  => 'integer',
        'elo_change_guest' => 'integer',
    ];

    // ─── Relationships ───────────────────────────────────────────────────────

    public function host(): BelongsTo
    {
        return $this->belongsTo(User::class, 'host_id');
    }

    public function guest(): BelongsTo
    {
        return $this->belongsTo(User::class, 'guest_id');
    }

    public function winner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'winner_id');
    }

    public function season(): BelongsTo
    {
        return $this->belongsTo(Season::class);
    }

    // ─── Helpers ─────────────────────────────────────────────────────────────

    public function isParticipant(User $user): bool
    {
        return $this->host_id === $user->id || $this->guest_id === $user->id;
    }

    public function hasHostSubmitted(): bool
    {
        return ! is_null($this->submitted_host_score_host);
    }

    public function hasGuestSubmitted(): bool
    {
        return ! is_null($this->submitted_guest_score_host);
    }

    public function scoresMatch(): bool
    {
        return $this->submitted_host_score_host  === $this->submitted_guest_score_host
            && $this->submitted_host_score_guest === $this->submitted_guest_score_guest;
    }
}
