package com.bsmlab.dfx.dfxconsole.framework.support.mybatis.handler;

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.*;

@MappedTypes(Long.class)
@MappedJdbcTypes(JdbcType.TIMESTAMP_WITH_TIMEZONE)
public class EpochMillisWithTimeZoneTypeHandler extends BaseTypeHandler<Long> {
    @Override
    public void setParameter(PreparedStatement ps, int i, Long parameter, JdbcType jdbcType) throws SQLException {
        if(parameter == 0L) {
            ps.setNull(i, Types.TIMESTAMP_WITH_TIMEZONE);
        }
        else {
            ps.setTimestamp(i, new Timestamp(parameter)); // 밀리초 → java.sql.Timestamp
        }
    }
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Long parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, new Timestamp(parameter)); // 밀리초 → java.sql.Timestamp
    }

    @Override
    public Long getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp ts = rs.getTimestamp(columnName);
        return ts == null ? null : ts.getTime();  // Timestamp → 밀리초 long
    }

    @Override
    public Long getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp ts = rs.getTimestamp(columnIndex);
        return ts == null ? null : ts.getTime();
    }

    @Override
    public Long getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp ts = cs.getTimestamp(columnIndex);
        return ts == null ? null : ts.getTime();
    }
}
