package com.cf.imes.framework.mybatis.core.type;

import com.cf.imes.framework.common.util.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
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;

/**
 * mb自定义压缩字符串到byte[]类型转换器
 *
 * @author Gqr
 * @since 2026/5/11 14:22
 */
public class CompressByteTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(
            PreparedStatement ps,
            int i,
            String parameter,
            JdbcType jdbcType
    ) throws SQLException {

        if (StringUtils.isBlank(parameter)) {
            ps.setBytes(i, null);
            return;
        }

        byte[] compressed = JsonUtils.zip(parameter);

        ps.setBytes(i, compressed);
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName)
            throws SQLException {

        byte[] bytes = rs.getBytes(columnName);

        return unzip(bytes);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {

        byte[] bytes = rs.getBytes(columnIndex);

        return unzip(bytes);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {

        byte[] bytes = cs.getBytes(columnIndex);

        return unzip(bytes);
    }

    private String unzip(byte[] bytes) {

        if (bytes == null || bytes.length == 0) {
            return null;
        }

        return JsonUtils.unzip(bytes);
    }
}
