package com.Modules.etl.handler;


import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;

@MappedTypes(LocalDateTime.class)
public class TimestamptzTypeHandler extends BaseTypeHandler<LocalDateTime> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    LocalDateTime parameter, JdbcType jdbcType)
            throws SQLException {
        if (parameter == null) {
            ps.setTimestamp(i, null);
        } else {
            // 转换为Timestamp
            ps.setTimestamp(i, Timestamp.valueOf(parameter));
        }
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnName);
        return convertToLocalDateTime(timestamp);
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnIndex);
        return convertToLocalDateTime(timestamp);
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        Timestamp timestamp = cs.getTimestamp(columnIndex);
        return convertToLocalDateTime(timestamp);
    }

    private LocalDateTime convertToLocalDateTime(Timestamp timestamp) {
        if (timestamp == null) {
            return null;
        }

        try {
            // 方法1: 直接从Timestamp转换
            return timestamp.toLocalDateTime();

            // 方法2: 通过Instant转换（处理时区）
            // Instant instant = timestamp.toInstant();
            // return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

        } catch (Exception e) {
            throw new RuntimeException("Failed to convert TIMESTAMPTZ to LocalDateTime", e);
        }
    }
}