<?php

namespace App\Models;

use App\Enums\Status;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * 后台用户扩展字段定义
 *
 * 定义后台用户(admin_users)可动态扩展的自定义字段，
 * 如工号、职称、专长等。应用可通过 app_id 标记来源，
 * 卸载时据此清理。
 */
class AdminUserExtField extends BaseModel
{
    protected $table = 'admin_user_ext_fields';

    public const CREATED_AT = 'create_time';
    public const UPDATED_AT = 'update_time';

    protected $fillable = [
        'field_name',
        'field_label',
        'field_type',
        'field_options',
        'app_id',
        'sort',
        'status',
    ];

    protected $casts = [
        'field_options' => 'array',
        'sort' => 'integer',
        'status' => Status::class,
    ];

    /**
     * 关联扩展数据
     */
    public function extData(): HasMany
    {
        return $this->hasMany(AdminUserExtData::class, 'field_id');
    }

    /**
     * 启用的字段
     */
    public function scopeEnabled(Builder $query): Builder
    {
        return $query->where('status', Status::ENABLED);
    }

    /**
     * 按应用筛选
     */
    public function scopeByApp(Builder $query, ?string $appId): Builder
    {
        if ($appId) {
            return $query->where('app_id', $appId);
        }
        return $query;
    }
}
