package cn.nianxx.thhotel.workflows.reservation.service.impl;

import cn.nianxx.thhotel.platform.message.common.result.SourceMessageRelatedContextResult;
import cn.nianxx.thhotel.platform.message.common.result.SourceMessageRelatedOrderResult;
import cn.nianxx.thhotel.platform.message.common.result.SourceMessageRelatedTaskResult;
import cn.nianxx.thhotel.platform.message.service.SourceMessageRelatedContextProvider;
import cn.nianxx.thhotel.workflows.reservation.common.dto.ReservationAiQueryOrderSnapshot;
import cn.nianxx.thhotel.workflows.reservation.common.dto.ReservationAiQueryTaskSnapshot;
import cn.nianxx.thhotel.workflows.reservation.common.enums.ReservationOrderKeyType;
import cn.nianxx.thhotel.workflows.reservation.common.enums.ReservationOrderVisibility;
import cn.nianxx.thhotel.workflows.reservation.repository.ReservationAiWorkflowRepository;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;

/**
 * Reservation 模块提供的 SourceMessage 关联上下文实现。用于邮件会话详情展示关联订单和任务摘要。
 */
@Service
public class ReservationSourceMessageRelatedContextProvider implements SourceMessageRelatedContextProvider {

    private final ReservationAiWorkflowRepository workflowRepository;

    /**
     * 注入 Reservation 工作流持久化边界，避免平台层直接依赖 reservation 内部表。
     */
    public ReservationSourceMessageRelatedContextProvider(ReservationAiWorkflowRepository workflowRepository) {
        this.workflowRepository = workflowRepository;
    }

    /**
     * 查询指定 SourceMessage 在 reservation 工作流中的订单和任务关联摘要。
     */
    @Override
    public SourceMessageRelatedContextResult findRelatedContext(String hotelId, Long sourceMessageId) {
        if (sourceMessageId == null) {
            return new SourceMessageRelatedContextResult(List.of(), List.of());
        }
        List<ReservationAiQueryTaskSnapshot> tasks = workflowRepository.findAiQueryTasksBySourceMessageIds(
                hotelId,
                List.of(sourceMessageId));
        Map<Long, ReservationAiQueryOrderSnapshot> ordersById = findRelatedOrders(hotelId, sourceMessageId, tasks);
        return new SourceMessageRelatedContextResult(
                ordersById.values().stream().map(this::toRelatedOrder).toList(),
                tasks.stream().map(this::toRelatedTask).toList());
    }

    /**
     * 合并来源消息直接创建的订单和任务当前挂靠订单，避免只展示其中一侧。
     */
    private Map<Long, ReservationAiQueryOrderSnapshot> findRelatedOrders(
            String hotelId,
            Long sourceMessageId,
            List<ReservationAiQueryTaskSnapshot> tasks) {
        Map<Long, ReservationAiQueryOrderSnapshot> ordersById = new LinkedHashMap<>();
        workflowRepository.findAiQueryOrdersBySourceMessageIds(hotelId, List.of(sourceMessageId))
                .stream()
                .filter(this::isVisibleBusinessOrder)
                .forEach(order -> ordersById.put(order.id(), order));
        List<Long> taskOrderIds = tasks.stream()
                .map(ReservationAiQueryTaskSnapshot::orderId)
                .distinct()
                .toList();
        workflowRepository.findAiQueryOrdersByIds(hotelId, taskOrderIds)
                .stream()
                .filter(this::isVisibleBusinessOrder)
                .forEach(order -> ordersById.put(order.id(), order));
        return ordersById;
    }

    /**
     * 邮件会话只展示真实业务订单，S000/S999 等隐藏技术订单只通过任务摘要可见。
     */
    private boolean isVisibleBusinessOrder(ReservationAiQueryOrderSnapshot order) {
        return order != null && !ReservationOrderVisibility.HIDDEN_SYSTEM.name().equals(order.orderVisibility());
    }

    /**
     * 转换订单快照为 SourceMessage 会话可展示的关联订单摘要。
     */
    private SourceMessageRelatedOrderResult toRelatedOrder(ReservationAiQueryOrderSnapshot order) {
        return new SourceMessageRelatedOrderResult(
                order.id().toString(),
                displayOrderKey(order),
                order.orderStatus());
    }

    /**
     * 转换任务快照为 SourceMessage 会话可展示的关联任务摘要。
     */
    private SourceMessageRelatedTaskResult toRelatedTask(ReservationAiQueryTaskSnapshot task) {
        return new SourceMessageRelatedTaskResult(
                task.id().toString(),
                task.orderId().toString(),
                task.systemTaskType(),
                task.taskSubtype(),
                task.taskStatus(),
                task.taskCardType());
    }

    /**
     * 生成订单展示键，优先真实业务号，其次临时订单号。
     */
    private String displayOrderKey(ReservationAiQueryOrderSnapshot order) {
        String activeBusinessKey = trimToNull(order.activeBusinessKey());
        if (activeBusinessKey != null) {
            return activeBusinessKey;
        }
        String orderBusinessKey = trimToNull(order.orderBusinessKey());
        if (orderBusinessKey != null) {
            return orderBusinessKey;
        }
        if (ReservationOrderKeyType.TEMPORARY.name().equals(order.orderKeyType())) {
            return order.temporaryOrderCode();
        }
        return order.displayName();
    }

    /**
     * 去除空白字符串，空字符串按 null 处理。
     */
    private String trimToNull(String value) {
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        return value.trim();
    }
}
