<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\UserExtFieldService;
use Illuminate\Http\Request;

/**
 * 后台用户扩展字段管理API
 */
class AdminUserExtFieldController extends Controller
{
    protected $service;

    public function __construct(UserExtFieldService $service)
    {
        $this->service = $service;
    }

    /**
     * 获取扩展字段列表
     */
    public function index()
    {
        return response()->json($this->service->listAdminFields());
    }

    /**
     * 创建扩展字段
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'field_name' => 'required|string|max:50|alpha_dash',
            'field_label' => 'required|string|max:50',
            'field_type' => 'nullable|string|in:text,number,select,textarea,switch,date,json',
            'field_options' => 'nullable|array',
            'app_id' => 'nullable|string|max:100',
            'sort' => 'nullable|integer',
            'status' => 'nullable|integer|in:0,1',
        ]);

        return response()->json($this->service->storeAdminField($validated));
    }

    /**
     * 更新扩展字段
     */
    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'field_name' => 'nullable|string|max:50|alpha_dash',
            'field_label' => 'nullable|string|max:50',
            'field_type' => 'nullable|string|in:text,number,select,textarea,switch,date,json',
            'field_options' => 'nullable|array',
            'sort' => 'nullable|integer',
            'status' => 'nullable|integer|in:0,1',
        ]);

        return response()->json($this->service->updateAdminField((int) $id, $validated));
    }

    /**
     * 删除扩展字段
     */
    public function destroy($id)
    {
        return response()->json($this->service->destroyAdminField((int) $id));
    }
}
