package com.ycwl.basic.controller.pc;

import com.ycwl.basic.integration.message.dto.ChannelsResponse;
import com.ycwl.basic.integration.message.dto.MessageListData;
import com.ycwl.basic.integration.message.service.MessageIntegrationService;
import com.ycwl.basic.utils.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/message/v1")
@RequiredArgsConstructor
public class MessageController {

    private final MessageIntegrationService messageService;

    @GetMapping("/messages")
    public ApiResponse<MessageListData> listMessages(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize,
            @RequestParam(required = false) String channelId,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String content,
            @RequestParam(required = false) String sendBiz,
            @RequestParam(required = false) String sentAtStart,
            @RequestParam(required = false) String sentAtEnd,
            @RequestParam(required = false) String createdAtStart,
            @RequestParam(required = false) String createdAtEnd
    ) {
        log.debug("PC|消息列表查询 page={}, pageSize={}, channelId={}, title={}, sendBiz={}", page, pageSize, channelId, title, sendBiz);
        if (pageSize > 100) {
            pageSize = 100;
        }
        try {
            MessageListData data = messageService.listMessages(page, pageSize, channelId, title, content, sendBiz,
                    sentAtStart, sentAtEnd, createdAtStart, createdAtEnd);
            return ApiResponse.success(data);
        } catch (Exception e) {
            log.error("PC|消息列表查询失败", e);
            return ApiResponse.fail("消息列表查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/channels")
    public ApiResponse<ChannelsResponse> listChannels() {
        log.debug("PC|获取消息通道列表");
        try {
            ChannelsResponse data = messageService.listChannels();
            return ApiResponse.success(data);
        } catch (Exception e) {
            log.error("PC|获取消息通道列表失败", e);
            return ApiResponse.fail("获取消息通道列表失败: " + e.getMessage());
        }
    }
}
