package tech.easyflow.admin.controller.common;

import jakarta.servlet.http.HttpServletRequest;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.dict.Dict;
import tech.easyflow.common.dict.DictItem;
import tech.easyflow.common.dict.DictLoader;
import tech.easyflow.common.dict.DictManager;
import tech.easyflow.common.web.exceptions.BusinessException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 提供已注册静态字典的查询接口。
 */
@RestController
@RequestMapping("/api/v1/dict/")
public class DictController {

    @Resource
    private DictManager dictManager;

    /**
     * 查询指定静态字典的选项。
     *
     * @param code 字典编码
     * @param keyword 搜索关键字
     * @param request HTTP 请求
     * @return 字典选项
     * @throws BusinessException 字典未注册时抛出
     */
    @GetMapping("/items/{code}")
    public Result<List<DictItem>> items(@PathVariable("code") String code, String keyword, HttpServletRequest request) {
        DictLoader loader = dictManager.getLoader(code);
        if (loader == null) {
            throw new BusinessException("字典不存在或不支持公共查询");
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        Dict dict = loader.load(keyword, parameterMap);
        if (dict == null) {
            return Result.ok(Collections.emptyList());
        }
        return Result.ok(dict.getItems());
    }

}
