<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Enums\AdminRoleStatus;
use App\Enums\AdminUserStatus;
use App\Services\DberpPermissionService;
use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'nickname',
        'login_account',
        'email',
        'password',
        'status',
        'last_login_at',
        'is_bootstrap_install_admin',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'last_login_at' => 'datetime',
            'password' => 'hashed',
            'status' => AdminUserStatus::class,
            'is_bootstrap_install_admin' => 'boolean',
        ];
    }

    public function adminRoles(): BelongsToMany
    {
        return $this->belongsToMany(DberpAdminRole::class, 'core_user_roles', 'user_id', 'role_id')
            ->withPivot(['user_type', 'guard_name'])
            ->withTimestamps()
            ->wherePivot('user_type', self::class);
    }

    public function dberpPermissionGrants(): HasMany
    {
        return $this->hasMany(DberpUserPermissionGrant::class, 'user_id');
    }

    /**
     * @return HasMany<DberpAdminMenuShortcut, $this>
     */
    public function dberpAdminMenuShortcuts(): HasMany
    {
        return $this->hasMany(DberpAdminMenuShortcut::class, 'admin_id');
    }

    public function canAccessPanel(Panel $panel): bool
    {
        if ($panel->getId() !== 'admin') {
            return false;
        }

        return $this->isAdminEnabled() && $this->hasExplicitBackofficeAccess();
    }

    public function isAdminEnabled(): bool
    {
        return ($this->status ?? AdminUserStatus::Enabled) === AdminUserStatus::Enabled;
    }

    public function hasExplicitBackofficeAccess(): bool
    {
        if ($this->isSuperAdmin()) {
            return true;
        }

        return app(DberpPermissionService::class)->grantedPermissionCodes($this) !== [];
    }

    public function isSuperAdmin(): bool
    {
        return $this->adminRoles()
            ->where('is_super_admin', true)
            ->where('status', AdminRoleStatus::Enabled->value)
            ->exists();
    }

    public function isBootstrapInstallAdmin(): bool
    {
        return (bool) $this->is_bootstrap_install_admin;
    }
}
