<?php

namespace App\Models;

use App\Enums\UserRole;
use App\Support\PublicMedia;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use NotificationChannels\WebPush\HasPushSubscriptions;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable, SoftDeletes, HasRoles, HasPushSubscriptions;

    protected $fillable = [
        'company_id', 'branch_id',
        'name', 'email', 'password',
        'phone', 'avatar_path',
        'locale', 'timezone',
        'is_active', 'last_login_at', 'last_login_ip',
    ];

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

    protected function casts(): array
    {
        return [
            'email_verified_at'        => 'datetime',
            'password'                 => 'hashed',
            'is_active'                => 'boolean',
            'last_login_at'            => 'datetime',
            'two_factor_confirmed_at'  => 'datetime',
        ];
    }

    /* ------------------------------------------------------------------
     | Relaciones
     |------------------------------------------------------------------*/

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function employee(): HasOne
    {
        return $this->hasOne(Employee::class);
    }

    /* ------------------------------------------------------------------
     | Helpers
     |------------------------------------------------------------------*/

    public function isSuperAdmin(): bool
    {
        return $this->hasRole(UserRole::SuperAdmin->value);
    }

    public function isCompanyAdmin(): bool
    {
        return $this->hasRole(UserRole::CompanyAdmin->value);
    }

    public function isEmployee(): bool
    {
        return $this->hasRole(UserRole::Employee->value);
    }

    public function dashboardRoute(): string
    {
        return match (true) {
            $this->isSuperAdmin()   => route('superadmin.dashboard'),
            $this->isCompanyAdmin() => route('tenant.dashboard'),
            $this->isEmployee()     => route('employee.dashboard'),
            default                 => route('dashboard'),
        };
    }

    public function getAvatarUrlAttribute(): ?string
    {
        return PublicMedia::url($this->avatar_path);
    }
}
