<?php

namespace App\Models\Auth;

use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use ModelTrait, SoftDeletes;

    protected $table = 'auth_user';

    protected $fillable = [
        'username',
        'password',
        'real_name',
        'email',
        'phone',
        'department_id',
        'avatar',
        'status',
        'last_login_at',
        'last_login_ip',
    ];

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

    protected $casts = [
        'status' => 'integer',
        'department_id' => 'integer',
        'last_login_at' => 'datetime',
    ];

    /**
     * 关联部门
     */
    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class, 'department_id');
    }

    /**
     * 关联角色
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'auth_user_role', 'user_id', 'role_id')
            ->withTimestamps();
    }

    /**
     * 获取用户的所有权限
     */
    public function permissions()
    {
        return $this->roles()->with('permissions');
    }

    /**
     * 检查用户是否有指定权限
     */
    public function hasPermission(string $permissionCode): bool
    {
        foreach ($this->roles as $role) {
            foreach ($role->permissions as $permission) {
                if ($permission->name === $permissionCode) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检查用户是否有指定角色
     */
    public function hasRole(string $roleCode): bool
    {
        return $this->roles()->where('code', $roleCode)->exists();
    }

    /**
     * 判断用户是否为超级管理员
     */
    public function isSuperAdmin(): bool
    {
        return $this->hasRole('super_admin');
    }

    /**
     * 获取 JWT 标识符
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * 获取 JWT 自定义声明
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}
