package com.njcn.relational.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Base64;

/**
 * Blob 字段 JSON 序列化器
 * 将数据库 Blob 类型转换为 Base64 字符串
 */
public class BlobSerializer extends JsonSerializer<Blob> {

    @Override
    public void serialize(Blob blob, JsonGenerator gen, SerializerProvider serializers)
            throws IOException {

        if (blob == null) {
            gen.writeNull();
            return;
        }

        try {
            // 获取 Blob 字节数组
            byte[] bytes = blob.getBytes(1, (int) blob.length());
            // 转换为 Base64
            String base64 = Base64.getEncoder().encodeToString(bytes);
            gen.writeString(base64);
        } catch (SQLException e) {
            gen.writeNull();
        }
    }
}
