package com.gxwebsoft.common.core.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * JSON 字符串 → 数组 序列化器
 * <p>
 * 数据库中 attachments 存储为 JSON 字符串，响应给前端时自动转成数组。
 *
 * @author WebSoft
 * @since 2026-03-30
 */
@Slf4j
public class JsonStringToArraySerializer extends JsonSerializer<String> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null || value.trim().isEmpty()) {
            gen.writeStartArray();
            gen.writeEndArray();
            return;
        }
        try {
            List<String> list = MAPPER.readValue(value,
                    MAPPER.getTypeFactory().constructCollectionType(List.class, String.class));
            gen.writeObject(list);
        } catch (Exception e) {
            // 解析失败（非JSON格式）就把原始字符串包成单元素数组
            log.warn("attachments 字段不是合法 JSON 数组，原样包装: {}", value);
            gen.writeStartArray();
            gen.writeString(value);
            gen.writeEndArray();
        }
    }
}
