package com.ai.da.common.task;

import com.ai.da.common.utils.SendEmailUtil;
import com.ai.da.mapper.primary.AccountMapper;
import com.ai.da.mapper.primary.SubscriptionInfoMapper;
import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.mapper.primary.entity.SubscriptionInfo;
import com.ai.da.service.StripeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class SubscriptionReminderTask {

    public final AccountMapper accountMapper;

    public final SubscriptionInfoMapper subscriptionInfoMapper;

    public final StripeService stripeService;

    // 订阅类型与提前天数的映射配置
    private static final Map<String, Integer> REMINDER_DAYS_CONFIG = new HashMap<>();

    static {
        REMINDER_DAYS_CONFIG.put("monthly", 7);
        REMINDER_DAYS_CONFIG.put("yearly", 14);
    }

    public void subscriptionReminder() {
        // 获取所有需要通知的订阅
        List<SubscriptionInfo> subscriptionInfos = getDueSubscriptions();

        for (SubscriptionInfo subscriptionInfo : subscriptionInfos) {
            Integer daysBefore = REMINDER_DAYS_CONFIG.get(subscriptionInfo.getType());
            if (daysBefore == null) {
                log.warn("未知的订阅类型: {}", subscriptionInfo.getType());
                continue;
            }
            String emailType = subscriptionInfo.getStatus().equals("active") ? "reminder_subscriber" : subscriptionInfo.getStatus().equals("canceled") ? "reminder_expire" : null;
            if (StringUtil.isNullOrEmpty(emailType)) {
                log.warn("未知订阅状态：{}", subscriptionInfo.getStatus());
                continue;
            }

            boolean success = stripeService.sendEmail(subscriptionInfo.getSubscriptionId(), "reminder_subscriber", null);
            if (success) {
                log.info("提前{}天向用户 {} 发送续订通知邮件，订阅类型: {}",
                        daysBefore, subscriptionInfo.getAccountId(), subscriptionInfo.getType());
            }
        }
    }

    private List<SubscriptionInfo> getDueSubscriptions() {
        List<SubscriptionInfo> results = new ArrayList<>();

        for (Map.Entry<String, Integer> entry : REMINDER_DAYS_CONFIG.entrySet()) {
            String subscriptionType = entry.getKey();
            int daysBefore = entry.getValue();

            results.addAll(getSubscriptionsDueInDays(subscriptionType, daysBefore));
        }

        return results;
    }

    private List<SubscriptionInfo> getSubscriptionsDueInDays(String subscriptionType, int daysBefore) {
        LocalDateTime targetDate = LocalDateTime.now().plusDays(daysBefore);
        LocalDateTime startOfDay = targetDate.toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = targetDate.toLocalDate().atTime(23, 59, 59);

        long startTimestamp = startOfDay.toEpochSecond(ZoneOffset.UTC);
        long endTimestamp = endOfDay.toEpochSecond(ZoneOffset.UTC);

        QueryWrapper<SubscriptionInfo> qw = new QueryWrapper<>();
        qw.ge("current_period_end", startTimestamp);
        qw.lt("current_period_end", endTimestamp);
//        qw.eq("status", "active");
        qw.eq("subscription_type", subscriptionType);

        return subscriptionInfoMapper.selectList(qw);
    }

    public void trialReminder() {
        // 今天的 00:00:00 和 23:59:59
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = LocalDateTime.now().toLocalDate().atTime(23, 59, 59);

        // 转为时间戳
        long startTimestamp = startOfDay.toEpochSecond(ZoneOffset.UTC);
        long endTimestamp = endOfDay.toEpochSecond(ZoneOffset.UTC);

        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().gt(Account::getValidEndTime, startTimestamp)
                .lt(Account::getValidEndTime, endTimestamp)
                .eq(Account::getSystemUser, 3);

        List<Account> accounts = accountMapper.selectList(queryWrapper);
        for (Account account : accounts) {
            String language = stripeService.getLanguage(account.getLanguage(), account.getCountry(), "reminder_trial");
            SendEmailUtil.subscriptionEmailReminder("reminder_trial", null, language, account.getUserEmail());
        }
    }


/*    public void subscriptionReminder(){
        // 提前7天的 00:00:00 和 23:59:59
        LocalDateTime startOfDay = LocalDateTime.now().plusDays(7).toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = LocalDateTime.now().plusDays(7).toLocalDate().atTime(23, 59, 59);

        // 转为时间戳
        long startTimestamp = startOfDay.toEpochSecond(ZoneOffset.UTC);
        long endTimestamp = endOfDay.toEpochSecond(ZoneOffset.UTC);

        QueryWrapper<SubscriptionInfo> qw = new QueryWrapper<>();
        qw.ge("current_period_end", startTimestamp);
        qw.lt("current_period_end", endTimestamp);
        qw.eq("status", "active");

        List<SubscriptionInfo> subscriptionInfos = subscriptionInfoMapper.selectList(qw);
        for (SubscriptionInfo subscriptionInfo : subscriptionInfos) {
            boolean b = sendEmail(subscriptionInfo.getSubscriptionId(), "reminder", null);
            if (b) log.info("提前7天向用户 {} 发送续订通知邮件", subscriptionInfo.getAccountId());
        }
    }*/
}
