<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, HasRoles, Notifiable;

    protected $fillable = [
        'discord_id', 'username', 'discord_username', 'avatar', 'email',
        'steam_id', 'steam_username',
        'elo', 'rank', 'wins', 'losses', 'draws',
        'goals_scored', 'goals_conceded', 'clean_sheets',
        'longest_win_streak', 'longest_lose_streak', 'current_streak',
        'is_banned', 'ban_reason',
    ];

    protected $hidden = ['remember_token'];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'is_banned'         => 'boolean',
        'elo'               => 'integer',
        'wins'              => 'integer',
        'losses'            => 'integer',
        'draws'             => 'integer',
        'current_streak'    => 'integer',
    ];

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

    public function hostedMatches(): HasMany
    {
        return $this->hasMany(GameMatch::class, 'host_id');
    }

    public function guestMatches(): HasMany
    {
        return $this->hasMany(GameMatch::class, 'guest_id');
    }

    public function tournaments(): HasMany
    {
        return $this->hasMany(TournamentParticipant::class);
    }

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

    public function allMatches()
    {
        return GameMatch::where('host_id', $this->id)
                        ->orWhere('guest_id', $this->id)
                        ->latest();
    }

    public function getDivision(): array
    {
        return getDivision($this->elo);
    }

    public function getWinRateAttribute(): float
    {
        $total = $this->wins + $this->losses + $this->draws;
        return $total > 0 ? round($this->wins / $total * 100, 1) : 0.0;
    }

    public function syncRank(): void
    {
        $div = getDivision($this->elo);
        $this->rank = $div['name'];
        $this->save();
    }
}
