package com.usky.issue.service.sync;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.usky.issue.domain.IssueSyncData;
import com.usky.issue.service.enums.SyncTypeEnum;
import com.usky.issue.service.util.SyncJsonMapper;
import org.springframework.util.StringUtils;

/**
 * 同步 payload 解析
 *
 * @author fyc
 * @date 2026-06-29
 */
public final class SyncPayloadSupport {

    private static final ObjectMapper OBJECT_MAPPER = SyncJsonMapper.INSTANCE;

    private SyncPayloadSupport() {
    }

    public static String buildUserDataKey(Long userId) {
        return SyncTypeEnum.USER.getCode() + "-" + userId;
    }

    public static String resolveBusinessPayload(String rawPayload) throws Exception {
        if (!StringUtils.hasText(rawPayload)) {
            return rawPayload;
        }
        try {
            IssueSyncData wrapper = OBJECT_MAPPER.readValue(rawPayload, IssueSyncData.class);
            if (StringUtils.hasText(wrapper.getPayload())) {
                return wrapper.getPayload();
            }
        } catch (Exception ignored) {
            // 非 IssueSyncData 包装，按业务 JSON 原样处理
        }
        return rawPayload;
    }

    public static String wrapBusinessPayload(Integer tenantId, String tableName, String dataKey,
                                             String businessPayload, Long syncVersion) throws Exception {
        IssueSyncData syncData = new IssueSyncData();
        syncData.setTenantId(tenantId);
        syncData.setTableName(tableName);
        syncData.setDataKey(dataKey);
        syncData.setPayload(businessPayload);
        syncData.setSyncVersion(syncVersion);
        return OBJECT_MAPPER.writeValueAsString(syncData);
    }
}
