package com.Modules.etl.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Base64;
import java.util.List;

/**
 * 字节数组类型处理器 - 达梦数据库兼容版本（JSON格式）
 * 
 * 将 Java byte[][] 与数据库 VARCHAR 列进行互转。
 * 存储格式: JSON 数组，每个元素为 Base64 编码字符串，如 ["YWJj","ZGVm"]
 * 空数组: 存储为 "[]"
 * null值: 存储为 NULL
 * 
 * 原 PostgreSQL 版本使用 createArrayOf("bytea", ...) 创建原生 bytea 数组，
 * 达梦数据库不兼容此 API，改为 VARCHAR + JSON + Base64 存储。
 */
@MappedTypes(byte[][].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ArrayByteTypeHandler extends BaseTypeHandler<byte[][]> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, byte[][] parameter, JdbcType jdbcType) throws SQLException {
        try {
            String[] encoded = new String[parameter.length];
            for (int j = 0; j < parameter.length; j++) {
                encoded[j] = Base64.getEncoder().encodeToString(parameter[j]);
            }
            ps.setString(i, MAPPER.writeValueAsString(encoded));
        } catch (JsonProcessingException e) {
            throw new SQLException("Failed to serialize byte[][] to JSON", e);
        }
    }

    @Override
    public byte[][] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseArray(rs.getString(columnName));
    }

    @Override
    public byte[][] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseArray(rs.getString(columnIndex));
    }

    @Override
    public byte[][] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseArray(cs.getString(columnIndex));
    }

    private byte[][] parseArray(String value) {
        if (value == null || value.isEmpty()) {
            return new byte[0][];
        }
        try {
            // JSON 格式: ["abc","def"]
            List<String> list = MAPPER.readValue(value, MAPPER.getTypeFactory().constructCollectionType(List.class, String.class));
            byte[][] result = new byte[list.size()][];
            for (int i = 0; i < list.size(); i++) {
                String s = list.get(i);
                result[i] = (s == null || s.isEmpty()) ? new byte[0] : Base64.getDecoder().decode(s);
            }
            return result;
        } catch (JsonProcessingException e) {
            // 兼容旧的逗号分隔格式
            String[] parts = value.split(",", -1);
            byte[][] result = new byte[parts.length][];
            for (int i = 0; i < parts.length; i++) {
                String part = parts[i].trim();
                result[i] = part.isEmpty() ? new byte[0] : Base64.getDecoder().decode(part);
            }
            return result;
        }
    }
}
