package cn.iocoder.yudao.module.llm.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

public class ListHashMapTypeHandler extends BaseTypeHandler<List<HashMap<String, Object>>> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<HashMap<String, Object>> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String jsonString = objectMapper.writeValueAsString(parameter);
            ps.setString(i, jsonString);
        } catch (Exception e) {
            throw new SQLException("Failed to convert List<HashMap<String, Object>> to JSON string", e);
        }
    }

    @Override
    public List<HashMap<String, Object>> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String jsonStr = rs.getString(columnName);
        return getListFromJson(jsonStr);
    }

    @Override
    public List<HashMap<String, Object>> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonStr = rs.getString(columnIndex);
        return getListFromJson(jsonStr);
    }

    @Override
    public List<HashMap<String, Object>> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonStr = cs.getString(columnIndex);
        return getListFromJson(jsonStr);
    }

    private List<HashMap<String, Object>> getListFromJson(String jsonStr) {
        if (jsonStr == null) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonStr, objectMapper.getTypeFactory().constructCollectionType(List.class, HashMap.class));
        } catch (Exception e) {
            return null;
        }
    }
}
