<?php

// app/Models/User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
        'type',
        'status',
        'metadata',
        'settings',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'status' => 'boolean',
        'metadata' => 'array',
        'settings' => 'array',
    ];

    /**
     * Relacionamentos específicos por tipo
     */
    public function merchant()
    {
        return $this->hasOne(Merchant::class);
    }

    public function fiscal()
    {
        return $this->hasOne(Fiscal::class);
    }

    public function staff()
    {
        return $this->hasOne(Staff::class);
    }

    /**
     * Verifica se o usuário é de um determinado tipo
     */
    public function isType(string $type): bool
    {
        return $this->type === $type;
    }

    public function isAdmin(): bool
    {
        return $this->type === 'admin' || $this->type === 'staff';
    }

    public function isFiscal(): bool
    {
        return $this->type === 'fiscal';
    }

    public function isStaff(): bool
    {
        return $this->type === 'staff';
    }

    /**
     * Obtém o perfil específico baseado no tipo
     */
    public function getProfileAttribute()
    {
        return match ($this->type) {
            'fiscal' => $this->fiscal,
            'staff', 'admin' => $this->staff ?? $this,
            default => null,
        };
    }

    /**
     * Verifica se o usuário está ativo
     */
    public function isActive(): bool
    {
        return $this->status === true;
    }

    /**
     * Relacionamentos de papéis e permissões
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles');
    }

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'user_permissions');
    }

    public function hasRole($role): bool
    {
        if (is_string($role)) {
            return $this->roles->contains('name', $role);
        }

        return (bool) $role->intersect($this->roles)->count();
    }

    public function hasPermission($permission): bool
    {
        if (is_string($permission)) {
            return $this->permissions->contains('name', $permission) ||
                   $this->roles->flatMap->permissions->contains('name', $permission);
        }

        return $permission->intersect($this->permissions)->count() > 0 ||
               $this->roles->flatMap->permissions->contains($permission);
    }
}
