<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Models\Dictionary;
use App\Models\DictionaryItem;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DictionaryController extends Controller
{
    public function index(): JsonResponse
    {
        $dictionaries = Dictionary::withCount('items')->orderByDesc('id')->get();
        return $this->success($dictionaries);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:50',
            'code' => 'required|string|max:50|unique:dictionaries,code',
            'description' => 'nullable|string|max:255',
        ]);

        $dict = Dictionary::create($data);
        return $this->success($dict, '创建成功');
    }

    /**
     * 字典项列表
     */
    public function items(Dictionary $dictionary): JsonResponse
    {
        return $this->success($dictionary->items);
    }

    /**
     * 新建字典项
     */
    public function storeItem(Request $request, Dictionary $dictionary): JsonResponse
    {
        $data = $request->validate([
            'label' => 'required|string|max:100',
            'value' => 'required|string|max:100',
            'sort' => 'nullable|integer',
            'status' => 'in:0,1',
        ]);

        $data['dictionary_id'] = $dictionary->id;
        $data['sort'] = $data['sort'] ?? 0;
        $item = DictionaryItem::create($data);
        return $this->success($item, '创建成功');
    }

    /**
     * 更新字典项
     */
    public function updateItem(Request $request, DictionaryItem $item): JsonResponse
    {
        $data = $request->validate([
            'label' => 'string|max:100',
            'value' => 'string|max:100',
            'sort' => 'nullable|integer',
            'status' => 'in:0,1',
        ]);

        $item->update($data);
        return $this->success($item, '更新成功');
    }

    /**
     * 删除字典项
     */
    public function destroyItem(DictionaryItem $item): JsonResponse
    {
        $item->delete();
        return $this->success(null, '删除成功');
    }

    public function destroy(Dictionary $dictionary): JsonResponse
    {
        if ($dictionary->is_system) {
            return $this->error('系统字典不可删除');
        }

        $dictionary->items()->delete();
        $dictionary->delete();
        return $this->success(null, '删除成功');
    }
}
