package shop.alien.util.encryption;

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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import shop.alien.util.common.SpringContextUtil;
import shop.alien.util.encryption.properties.EncryptProperties;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * MyBatis 数据库字段加解密类型转换器
 * 基于 AES/CBC/PKCS5Padding
 * 使用方式：在实体类字段上添加 @TableField(typeHandler = EncryptTypeHandler.class)
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(String.class)
public class EncryptTypeHandler extends BaseTypeHandler<String> {

    private static final Logger log = LoggerFactory.getLogger(EncryptTypeHandler.class);

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        EncryptProperties properties = SpringContextUtil.getBean(EncryptProperties.class);
        if (properties != null && properties.isDbEnabled() && parameter != null) {
            String encrypted = StandardAesUtil.encrypt(parameter, properties.getKey(), properties.getIv());
            ps.setString(i, encrypted);
        } else {
            ps.setString(i, parameter);
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return decrypt(rs.getString(columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return decrypt(rs.getString(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return decrypt(cs.getString(columnIndex));
    }

    private String decrypt(String value) {
        if (value == null || value.isEmpty()) {
            return value;
        }
        EncryptProperties properties = SpringContextUtil.getBean(EncryptProperties.class);
        if (properties != null && properties.isDbEnabled()) {
            try {
                String decrypted = StandardAesUtil.decrypt(value, properties.getKey(), properties.getIv());
                return decrypted != null ? decrypted : value;
            } catch (Exception e) {
                log.error("数据库字段解密失败，返回原值: {}", e.getMessage());
                return value;
            }
        }
        return value;
    }
}
