package org.xyzh.ai.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.xyzh.api.ai.dto.PromptCard;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description 提示卡片列表类型处理器（JSONB <-> List<PromptCard>）
 * @filename PromptCardsTypeHandler.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-12-17
 */
@MappedTypes({List.class})
public class PromptCardsTypeHandler extends BaseTypeHandler<List<PromptCard>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<PromptCard> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null || parameter.isEmpty()) {
            ps.setString(i, "[]");
        } else {
            ps.setString(i, JSON.toJSONString(parameter));
        }
    }

    @Override
    public List<PromptCard> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String jsonString = rs.getString(columnName);
        return parseToList(jsonString);
    }

    @Override
    public List<PromptCard> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonString = rs.getString(columnIndex);
        return parseToList(jsonString);
    }

    @Override
    public List<PromptCard> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonString = cs.getString(columnIndex);
        return parseToList(jsonString);
    }

    private List<PromptCard> parseToList(String jsonString) {
        if (jsonString == null || jsonString.trim().isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return JSON.parseObject(jsonString, new TypeReference<List<PromptCard>>() {});
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
}
