<?php

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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');
    }

    /**
     * @return HasMany<DberpOfficialNewsRead, $this>
     */
    public function officialNewsReads(): HasMany
    {
        return $this->hasMany(DberpOfficialNewsRead::class);
    }

    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;
    }
}
