<?php

namespace App\Models;

use App\Enums\RolePrincipal;
use App\Enums\StatutCompteUser;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Str;

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

    protected $fillable = [
        'uuid', 'email', 'telephone', 'password',
        'role', 'statut', 'avatar', 'derniere_connexion_at',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'telephone_verified_at' => 'datetime',
        'derniere_connexion_at' => 'datetime',
        'role' => RolePrincipal::class,
        'statut' => StatutCompteUser::class,
    ];

    protected static function boot(): void
    {
        parent::boot();
        static::creating(fn($user) => $user->uuid ??= Str::uuid());
    }

    // Relations
    public function client(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(Client::class);
    }

    public function candidat(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(Candidat::class);
    }

    // Email verification
    public function sendEmailVerificationNotification(): void
    {
        $this->notify(new \App\Notifications\VerifyEmailNotification());
    }

    // Password reset
    public function sendPasswordResetNotification($token): void
    {
        $this->notify(new \App\Notifications\ResetPasswordNotification($token));
    }

    // Profile completion
    public function isProfileComplete(): bool
    {
        if ($this->isClient()) {
            $client = $this->client;
            return $client && $client->profilEstComplet();
        }

        if ($this->isCandidat()) {
            $candidat = $this->candidat;
            return $candidat && $candidat->profilEstComplet();
        }

        // Pour les admins, on considère que le profil est toujours complet
        return true;
    }

    // Helpers
    public function isAdmin(): bool
    {
        return in_array($this->role->value, ['admin', 'super_admin']);
    }

    public function isClient(): bool
    {
        return $this->role->value === 'client';
    }

    public function isCandidat(): bool
    {
        return $this->role->value === 'candidat';
    }

    public function isSuperAdmin(): bool
    {
        return $this->role->value === 'super_admin';
    }
}
