package com.sino.mci.inbound.webhook;

import com.sino.mci.inbound.entity.MessageEvent;
import com.sino.mci.inbound.intent.IntentResult;
import com.sino.mci.shared.util.JsonUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 入站 webhook 结构化 payload 构造器。
 *
 * <p>将 {@link MessageEvent} 与意图识别结果转换为业务系统可消费的标准 JSON 结构，
 * 字段命名与架构文档 1.8 节保持一致（snake_case）。</p>
 */
@Component
public class WebhookPayloadBuilder {

    private static final DateTimeFormatter ISO_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

    public Map<String, Object> buildPayload(MessageEvent event, IntentResult intent) {
        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("event_id", event.getEventId());
        payload.put("tenant_code", event.getTenantCode());
        payload.put("channel_type", event.getChannelType());
        payload.put("direction", mapDirection(event.getDirection()));
        payload.put("event_type", event.getEventType());
        payload.put("conversation_id", event.getConversationId());
        payload.put("person_id", event.getPersonId());
        payload.put("account_id", event.getAccountId());
        payload.put("content", parseJson(event.getContent()));
        payload.put("intent", buildIntentMap(intent));
        payload.put("business_context", parseJson(event.getBusinessContext()));
        payload.put("raw_payload", parseJson(event.getRawPayload()));
        payload.put("create_time", formatTime(event.getCreateTime()));
        return payload;
    }

    private Object buildIntentMap(IntentResult intent) {
        if (intent == null) {
            return null;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("intent", intent.getIntent());
        map.put("confidence", intent.getConfidence());
        map.put("slots", intent.getSlots());
        map.put("missing_slots", intent.getMissingSlots());
        map.put("requires_confirmation", intent.isRequiresConfirmation());
        return map;
    }

    @SuppressWarnings("unchecked")
    private Object parseJson(String json) {
        if (json == null || json.isBlank()) {
            return null;
        }
        Object result = JsonUtils.fromJson(json, Object.class);
        return result != null ? result : json;
    }

    private String mapDirection(Integer direction) {
        if (direction == null) {
            return "in";
        }
        return switch (direction) {
            case 1 -> "in";
            case 2 -> "out";
            default -> String.valueOf(direction);
        };
    }

    private String formatTime(LocalDateTime time) {
        if (time == null) {
            return null;
        }
        return time.format(ISO_FORMATTER);
    }
}
