package com.sino.mci.channel;

import com.sino.mci.channel.entity.ChannelAccount;
import com.sino.mci.channel.repository.ChannelAccountMapper;
import com.sino.mci.channel.service.ChannelAccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(properties = {
        "spring.rabbitmq.listener.simple.auto-startup=false",
        "spring.main.allow-bean-definition-overriding=true",
        "channel.account.health.interval=31536000000"
})
@Transactional
class ChannelAccountHeartbeatTest {

    private static final String TENANT_CODE = "heartbeat-" + UUID.randomUUID().toString().substring(0, 8);
    private static final String ACCOUNT_ID = "heartbeat-account-" + UUID.randomUUID().toString().substring(0, 8);

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ChannelAccountMapper accountMapper;

    @Autowired
    private ChannelAccountService accountService;

    @Test
    void shouldUpdateAccountStatusOnHeartbeat() throws Exception {
        createAccount();

        String payload = String.format("{\"accountId\":\"%s\",\"riskLevel\":30}", ACCOUNT_ID);
        mockMvc.perform(post("/msg-platform/api/v1/channel-account/heartbeat")
                        .contextPath("/msg-platform")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(payload))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(0))
                .andExpect(jsonPath("$.data.accountId").value(ACCOUNT_ID))
                .andExpect(jsonPath("$.data.onlineStatus").value(1))
                .andExpect(jsonPath("$.data.riskLevel").value(30));

        ChannelAccount account = findAccount();
        assertThat(account.getOnlineStatus()).isEqualTo(1);
        assertThat(account.getRiskLevel()).isEqualTo(30);
        assertThat(account.getLastHeartbeat()).isNotNull();
    }

    @Test
    void shouldMarkAccountOfflineWhenHeartbeatTimeout() {
        ChannelAccount account = createAccount();
        account.setOnlineStatus(1);
        account.setLastHeartbeat(LocalDateTime.now().minusSeconds(150));
        accountMapper.updateById(account);

        int offlineCount = accountService.checkOfflineAccounts(120);

        assertThat(offlineCount).isEqualTo(1);
        ChannelAccount updated = accountMapper.selectById(account.getId());
        assertThat(updated.getOnlineStatus()).isEqualTo(0);
    }

    @Test
    void shouldKeepOnlineAccountWhenHeartbeatWithinTimeout() {
        ChannelAccount account = createAccount();
        account.setOnlineStatus(1);
        account.setLastHeartbeat(LocalDateTime.now().minusSeconds(60));
        accountMapper.updateById(account);

        int offlineCount = accountService.checkOfflineAccounts(120);

        assertThat(offlineCount).isEqualTo(0);
        ChannelAccount updated = accountMapper.selectById(account.getId());
        assertThat(updated.getOnlineStatus()).isEqualTo(1);
    }

    private ChannelAccount createAccount() {
        ChannelAccount account = new ChannelAccount();
        account.setTenantCode(TENANT_CODE);
        account.setAccountType(3);
        account.setChannelType("wechat_personal");
        account.setAccountId(ACCOUNT_ID);
        account.setAccountName("心跳测试账号");
        account.setOnlineStatus(0);
        account.setRiskLevel(0);
        account.setStatus(1);
        accountMapper.insert(account);
        return account;
    }

    private ChannelAccount findAccount() {
        return accountMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ChannelAccount>()
                        .eq(ChannelAccount::getTenantCode, TENANT_CODE)
                        .eq(ChannelAccount::getAccountId, ACCOUNT_ID));
    }
}
