<?php

namespace Kylin\Dictionary\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\Dictionary\Models\DictItem;
use Kylin\Dictionary\Models\DictType;
use Kylin\Dictionary\Services\DictionaryService;

/**
 * 字典控制器
 *
 * 提供字典类型和字典项的查询 API，支持缓存加速。
 *
 * 合规要求：
 *  - 依据等保 2.0 (GB/T 22239) 8.1.4.1，字典管理需进行访问控制
 *  - 依据等保 2.0 (GB/T 22239) 8.1.4.6，字典增删改操作需记录审计日志
 */
class DictionaryController extends BaseController
{
    public function __construct(private readonly DictionaryService $service) {}

    public function types(): JsonResponse
    {
        $this->authorize('viewAny', DictType::class);

        return ApiResponse::success(DictType::with('items')->get());
    }

    public function storeType(Request $request): JsonResponse
    {
        $this->authorize('create', DictType::class);

        $data = $request->validate([
            'code' => 'required|string|max:50|unique:kylin_dict_types,code',
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:255',
        ]);
        return ApiResponse::created($this->service->createType($data['code'], $data['name'], $data['description'] ?? null));
    }

    public function items(string $code): JsonResponse
    {
        $this->authorize('viewAny', DictItem::class);

        return ApiResponse::success($this->service->getItemsByCode($code));
    }

    public function storeItem(Request $request, string $code): JsonResponse
    {
        $this->authorize('create', DictItem::class);

        $type = DictType::where('code', $code)->firstOrFail();
        $data = $request->validate([
            'label' => 'required|string|max:100',
            'value' => 'required|string|max:100',
            'sort' => 'nullable|integer',
            'description' => 'nullable|string|max:255',
        ]);
        return ApiResponse::created($this->service->createItem(
            $type->id, $data['label'], $data['value'], $data['sort'] ?? 0, $data['description'] ?? null
        ));
    }

    public function deleteItem(int $id): JsonResponse
    {
        $item = DictItem::findOrFail($id);
        $this->authorize('delete', $item);

        $item->delete();
        return ApiResponse::success(null, '删除成功');
    }
}