<?php

namespace App\Models;

use App\Enums\UserRole;
use App\Notifications\VerifyEmailNotification;
use Filament\Models\Contracts\FilamentUser;
use Filament\Models\Contracts\HasName;
use Filament\Panel;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable implements FilamentUser, HasName, MustVerifyEmail
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasApiTokens, HasFactory, HasUuids, Notifiable, SoftDeletes;

    /**
     * The primary key type.
     *
     * @var string
     */
    protected $keyType = 'string';

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'username',
        'email',
        'password',
        'role',
        'xp',
        'avatar_uri',
        'participations',
        'victories',
        'level_id',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'next_level_xp',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'role' => UserRole::class,
        ];
    }

    public function participations()
    {
        return $this->belongsToMany(Hunts::class, 'hunt_participants', 'user_id', 'hunt_id')
            ->withPivot(['current_step_number', 'status'])
            ->withTimestamps();
    }

    public function currentLevel(): BelongsTo
    {
        return $this->belongsTo(Level::class, 'level_id');
    }

    public function sendEmailVerificationNotification(): void
    {
        $this->notify(new VerifyEmailNotification);
    }

    public function updateLevel(): void
    {
        $level = Level::where('xpThreshold', '<=', $this->xp)
            ->orderBy('xpThreshold', 'desc')
            ->first();
        if ($level && $this->level_id !== $level->id) {
            $this->level_id = $level->id;
            $this->save();
        }
    }

    public function getNextLevelXpAttribute(): ?int
    {
        // Si l'XP est null, on ne peut pas comparer avec >
        // On retourne le premier niveau disponible
        if ($this->xp === null) {
            return Level::orderBy('xpThreshold', 'asc')
                ->value('xpThreshold');
        }

        return Level::where('xpThreshold', '>', $this->xp)
            ->orderBy('xpThreshold', 'asc')
            ->value('xpThreshold');
    }

    public function getFilamentName(): string
    {
        return $this->username;
    }

    public function canAccessPanel(Panel $panel): bool
    {
        return $this->role === UserRole::ADMIN || $this->role === UserRole::ORGA;
    }

    public function isAdmin(): bool
    {
        return $this->role === UserRole::ADMIN;
    }

    public function isOrga(): bool
    {
        return $this->role === UserRole::ORGA;
    }
}
