<?php

namespace App\Models;

use App\Enums\UserStatus;
use App\Enums\UserType;
use Database\Factories\UserFactory;
use App\Services\Notifications\EventNotificationService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, HasRoles, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'phone',
        'password',
        'status',
        'user_type',
        'two_factor_enabled',
        'is_primary_admin',
        'department_id',
        'designation_id',
    ];

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

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'status' => UserStatus::class,
            'user_type' => UserType::class,
            'two_factor_enabled' => 'boolean',
            'is_primary_admin' => 'boolean',
        ];
    }

    public function isPrimaryAdmin(): bool
    {
        return (bool) $this->is_primary_admin;
    }

    public function hasSuperAdminRole(): bool
    {
        return $this->hasRole(config('permissions.super_admin_role', 'Super Admin'));
    }

    public function isStaff(): bool
    {
        return $this->user_type === UserType::Staff;
    }

    public function isCustomer(): bool
    {
        return $this->user_type === UserType::Customer;
    }

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

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

    public function isActive(): bool
    {
        return $this->status === UserStatus::Active;
    }

    public function isSuspended(): bool
    {
        return $this->status === UserStatus::Suspended;
    }

    public function sendPasswordResetNotification($token): void
    {
        app(EventNotificationService::class)->send('forgot_password', $this, [
            'reset_url' => url(route('password.reset', [
                'token' => $token,
                'email' => $this->email,
            ], false)),
        ]);
    }
}
