package org.xyzh.common.jdbc.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
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.Arrays;
import java.util.List;

/**
 * @description    PostgreSQL VARCHAR数组类型处理器
 * @filename    StringArrayTypeHandler.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-15
 */
@MappedTypes({List.class})
public class StringArrayTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null || parameter.isEmpty()) {
            ps.setArray(i, null);
        } else {
            ps.setArray(i, ps.getConnection().createArrayOf("varchar", parameter.toArray()));
        }
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        java.sql.Array array = rs.getArray(columnName);
        return parseArray(array);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        java.sql.Array array = rs.getArray(columnIndex);
        return parseArray(array);
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        java.sql.Array array = cs.getArray(columnIndex);
        return parseArray(array);
    }

    private List<String> parseArray(java.sql.Array array) throws SQLException {
        if (array == null) {
            return null;
        }
        Object[] objects = (Object[]) array.getArray();
        return new ArrayList<>(Arrays.asList((String[]) objects));
    }
}
