package com.ycwl.basic.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

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

/**
 * Long类型列表的TypeHandler
 * 用于处理数据库JSON字段与Java List<Long>之间的转换
 */
@Slf4j
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class LongListTypeHandler extends BaseTypeHandler<List<Long>> {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final TypeReference<List<Long>> typeReference = new TypeReference<List<Long>>() {};

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
            log.debug("序列化Long列表: {}", json);
        } catch (JsonProcessingException e) {
            log.error("序列化Long列表失败", e);
            throw new SQLException("序列化Long列表失败", e);
        }
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJson(json, columnName);
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJson(json, "columnIndex:" + columnIndex);
    }

    @Override
    public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJson(json, "columnIndex:" + columnIndex);
    }

    private List<Long> parseJson(String json, String source) {
        if (json == null || json.trim().isEmpty() || "null".equals(json)) {
            log.debug("从{}获取的JSON为空，返回空列表", source);
            return new ArrayList<>();
        }

        try {
            List<Long> result = objectMapper.readValue(json, typeReference);
            if (result == null) {
                log.debug("从{}反序列化得到null，返回空列表", source);
                return new ArrayList<>();
            }
            log.debug("从{}反序列化Long列表成功，数量: {}", source, result.size());
            return result;
        } catch (JsonProcessingException e) {
            log.error("从{}反序列化Long列表失败，JSON: {}", source, json, e);
            return new ArrayList<>();
        }
    }
}
