<?php

namespace App\Models;

use App\Enums\Status;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Builder;
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 AdminUser extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    protected $table = 'admin_users';

    public const CREATED_AT = 'create_time';

    public const UPDATED_AT = 'update_time';

    protected $fillable = [
        'username',
        'password',
        'name',
        'email',
        'phone',
        'avatar',
        'status',
        'last_login_at',
        'last_login_ip',
        'login_count',
        'password_changed_at',
    ];

    protected $hidden = [
        'password',
    ];

    protected $casts = [
        'status' => Status::class,
        'password_changed_at' => 'datetime',
    ];

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(AdminRole::class, 'admin_user_roles', 'user_id', 'role_id');
    }

    /**
     * 扩展数据（动态字段值）
     */
    public function extData(): HasMany
    {
        return $this->hasMany(AdminUserExtData::class, 'admin_user_id');
    }

    public function isSuperAdmin(): bool
    {
        return $this->roles()->where('code', 'super_admin')->exists();
    }

    public function getAllPermissions(): array
    {
        return $this->roles()
            ->where('status', Status::ENABLED)
            ->with(['permissions' => function ($query) {
                $query->where('admin_permissions.status', Status::ENABLED);
            }])
            ->get()
            ->pluck('permissions')
            ->flatten()
            ->pluck('code')
            ->unique()
            ->values()
            ->toArray();
    }

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

        return in_array($code, $this->getAllPermissions());
    }

    public function scopeEnabled(Builder $query): Builder
    {
        return $query->where('status', Status::ENABLED);
    }
}
