package com.sino.mci.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sino.mci.admin.dto.DashboardStatsResponse;
import com.sino.mci.admin.security.AuthContext;
import com.sino.mci.channel.entity.ChannelAccount;
import com.sino.mci.channel.entity.ChannelSubject;
import com.sino.mci.channel.entity.Conversation;
import com.sino.mci.channel.repository.ChannelAccountMapper;
import com.sino.mci.channel.repository.ChannelSubjectMapper;
import com.sino.mci.channel.repository.ConversationMapper;
import com.sino.mci.send.entity.SendRecord;
import com.sino.mci.send.repository.SendRecordMapper;
import com.sino.mci.shared.web.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@RestController
@RequestMapping("/api/v1/dashboard")
@RequiredArgsConstructor
public class DashboardController {

    private final ChannelSubjectMapper subjectMapper;
    private final ChannelAccountMapper accountMapper;
    private final ConversationMapper conversationMapper;
    private final SendRecordMapper sendRecordMapper;

    @GetMapping("/stats")
    public ApiResponse<DashboardStatsResponse> stats() {
        String tenantCode = AuthContext.currentTenantCode();
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);

        DashboardStatsResponse response = new DashboardStatsResponse();
        response.setSubjectCount(subjectMapper.selectCount(
                new LambdaQueryWrapper<ChannelSubject>()
                        .eq(ChannelSubject::getTenantCode, tenantCode)
                        .eq(ChannelSubject::getStatus, 1)));
        response.setAccountCount(accountMapper.selectCount(
                new LambdaQueryWrapper<ChannelAccount>()
                        .eq(ChannelAccount::getTenantCode, tenantCode)
                        .eq(ChannelAccount::getStatus, 1)));
        response.setConversationCount(conversationMapper.selectCount(
                new LambdaQueryWrapper<Conversation>()
                        .eq(Conversation::getTenantCode, tenantCode)
                        .eq(Conversation::getStatus, 1)));
        response.setSentToday(sendRecordMapper.selectCount(
                new LambdaQueryWrapper<SendRecord>()
                        .eq(SendRecord::getTenantCode, tenantCode)
                        .ge(SendRecord::getSendTime, startOfDay)
                        .le(SendRecord::getSendTime, endOfDay)));
        return ApiResponse.ok(response);
    }
}
