<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;

use App\Enums\Gender;
use App\Traits\HasApiTokenAuth;
use App\Traits\HasRoles;
use App\Traits\QueryScopeTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokenAuth, HasRoles, QueryScopeTrait;

    protected $fillable = [
        'document_number',
        'names',
        'paternal_surname',
        'maternal_surname',
        'gender',
        'birth_date',
        'email',
        'phone_number',
        'photo_profile',
        'password',
        'active',
    ];

    // Columnas donde se puede buscar (texto general)
    public array $searchable = ['document_number', 'names', 'paternal_surname', 'maternal_surname', 'email'];

    // Columnas por las que se puede ordenar
    public array $sortable = ['id', 'document_number', 'names', 'paternal_surname', 'maternal_surname', 'email'];

    // Relaciones que se pueden incluir
    public array $allowedIncludes = ['roles', 'roles.permissions'];

    // Columnas por las que se puede filtrar específicamente
    public array $filterable = ['active', 'document_number', 'names', 'paternal_surname', 'maternal_surname', 'email'];

    protected $hidden = [
        'token_expires_at',
        'access_token',
        'password',
        'remember_token',
        'created_at',
        'updated_at',
        'last_login_at',
    ];

    protected $appends = ['user_type', 'photo_profile_url'];

    protected $casts = [
        'token_expires_at' => 'datetime',
        'last_login_at' => 'datetime',
        'email_verified_at' => 'datetime',
        'active' => 'boolean',
        'birth_date' => 'date',
        'gender' => Gender::class,
    ];

    // Accessor para user_type (necesario para $appends)
    public function getUserTypeAttribute(): string
    {
        return 'admin';
    }

    // Obtiene la URL completa de la foto de perfil
    public function getPhotoProfileUrlAttribute(): ?string
    {
        if (!$this->photo_profile) {
            return null;
        }

        // Si ya es una URL completa, retornarla
        if (filter_var($this->photo_profile, FILTER_VALIDATE_URL)) {
            return $this->photo_profile;
        }

        // Generar URL completa con el dominio del backend
        return url('storage/' . $this->photo_profile);
    }
}
