package cn.nianxx.thhotel.platform.message.control;

import cn.nianxx.thhotel.platform.message.common.result.SourceMessagePageResult;
import cn.nianxx.thhotel.platform.message.common.result.SourceMessageConversationResult;
import cn.nianxx.thhotel.platform.message.common.result.SourceMessageOriginalResponse;
import cn.nianxx.thhotel.platform.message.common.request.SourceMessageOriginalAccessRequest;
import cn.nianxx.thhotel.platform.message.common.request.SourceMessageQueryRequest;
import cn.nianxx.thhotel.platform.message.service.SourceMessageConversationService;
import cn.nianxx.thhotel.platform.message.service.SourceMessageOriginalService;
import cn.nianxx.thhotel.platform.message.service.SourceMessageQueryService;
import cn.nianxx.thhotel.platform.message.common.dto.SourceMessageSummaryResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

/**
 * SourceMessage Inbox 安全查询接口。该 Controller 不返回正文、HTML、附件 URL 或原始 payload。
 */
@RestController
@RequestMapping("/api/source-messages")
public class SourceMessageController {

    private final SourceMessageQueryService queryService;
    private final SourceMessageOriginalService originalService;
    private final SourceMessageConversationService conversationService;

    /**
     * 注入 SourceMessage 查询与原文读取服务，Controller 不直接访问 Mapper 或 Repository。
     */
    public SourceMessageController(
            SourceMessageQueryService queryService,
            SourceMessageOriginalService originalService,
            SourceMessageConversationService conversationService) {
        this.queryService = queryService;
        this.originalService = originalService;
        this.conversationService = conversationService;
    }

    /**
     * 分页查询 SourceMessage Inbox 安全摘要，普通列表不返回正文、HTML、附件 URL 或原始 payload。
     */
    @GetMapping
    public SourceMessagePageResult<SourceMessageSummaryResponse> list(
            @RequestParam(required = false) String hotelId,
            @RequestParam(required = false) String externalMessageId,
            @RequestParam(required = false) String externalConversationId,
            @RequestParam(required = false) String captureStatus,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize) {
        return queryService.query(new SourceMessageQueryRequest(
                hotelId,
                externalMessageId,
                externalConversationId,
                captureStatus,
                pageNum,
                pageSize
        ));
    }

    /**
     * 读取单条 SourceMessage Inbox 安全详情，用于排查消息是否已入站。
     */
    @GetMapping("/{id}")
    public SourceMessageSummaryResponse detail(@PathVariable Long id) {
        return queryService.getSummary(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "source message not found"));
    }

    /**
     * 读取 SourceMessage 原文内容。该接口必须携带受控访问口令、调用方和访问场景，并会写入审计。
     */
    @GetMapping("/{id}/original")
    public SourceMessageOriginalResponse original(
            @PathVariable Long id,
            @RequestHeader(name = "X-TH-Hotel-Source-Original-Read-Key", required = false) String accessKey,
            @RequestHeader(name = "X-TH-Hotel-Actor", required = false) String actorId,
            @RequestHeader(name = "X-TH-Hotel-Access-Scene", required = false) String accessScene) {
        if (!originalService.canReadOriginal(accessKey)) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "source message original read denied");
        }
        if (!hasText(actorId) || !hasText(accessScene)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "actor and access scene are required");
        }
        return originalService.readOriginal(id, new SourceMessageOriginalAccessRequest(actorId, accessScene))
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "source message not found"));
    }

    /**
     * 读取指定 SourceMessage 所在邮件会话完整详情。该接口由后端内部记录原文读取审计，前端不传原文 key。
     */
    @GetMapping("/{id}/conversation")
    public SourceMessageConversationResult conversation(@PathVariable Long id) {
        return conversationService.getConversation(id)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "source message not found"));
    }

    /**
     * 校验请求头文本是否有效，避免空白调用方或场景进入审计记录。
     */
    private boolean hasText(String value) {
        return value != null && !value.trim().isEmpty();
    }
}
