<?php

namespace App\Models;

use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'username',
        'email',
        'google_id',
        'password',
        'avatar_url',
        'favorite_team_id',
        'total_points',
        'fan_level',
        'streak_days',
        'last_checkin_date',
        'device_token',
        'notify_match_start',
        'notify_results',
        'notify_polls',
        'notify_leaderboard',
        'is_admin',
        'is_banned',
        'is_anonymized',
        'theme_preference',
    ];

    protected $hidden = [
        'password',
        'remember_token',
        'google_id',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at'    => 'datetime',
            'last_checkin_date'    => 'date',
            'password'             => 'hashed',
            'is_admin'             => 'boolean',
            'is_banned'            => 'boolean',
            'is_anonymized'        => 'boolean',
            'notify_match_start'   => 'boolean',
            'notify_results'       => 'boolean',
            'notify_polls'         => 'boolean',
            'notify_leaderboard'   => 'boolean',
        ];
    }

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

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

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

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

    public function badges(): BelongsToMany
    {
        return $this->belongsToMany(Badge::class, 'user_badges')->withTimestamps();
    }

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

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

    public function isAdmin(): bool
    {
        return (bool) $this->is_admin;
    }

    public function isBanned(): bool
    {
        return (bool) $this->is_banned;
    }

    public function isAnonymized(): bool
    {
        return (bool) $this->is_anonymized;
    }
}
