package com.example.demo.config;

import com.example.demo.model.MembershipLevel;
import com.example.demo.model.UserMembership;
import com.example.demo.model.PaymentStatus;
import com.example.demo.repository.MembershipLevelRepository;
import com.example.demo.repository.UserMembershipRepository;
import com.example.demo.repository.PaymentRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Component
public class DataInitializer implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

    private final MembershipLevelRepository membershipLevelRepository;
    private final UserMembershipRepository userMembershipRepository;
    private final PaymentRepository paymentRepository;

    public DataInitializer(MembershipLevelRepository membershipLevelRepository,
                           UserMembershipRepository userMembershipRepository,
                           PaymentRepository paymentRepository) {
        this.membershipLevelRepository = membershipLevelRepository;
        this.userMembershipRepository = userMembershipRepository;
        this.paymentRepository = paymentRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        initMembershipLevels();
    }

    @Transactional
    private void initMembershipLevels() {
        if (membershipLevelRepository.count() == 0) {
            // ===== 全新数据库：创建 4 个等级 =====
            logger.info("初始化会员等级数据...");
            createAllLevels();
            logger.info("✅ 会员等级数据初始化完成，共{}条", membershipLevelRepository.count());
        } else {
            // ===== 已有数据：检查是否需要迁移（添加 starter 等级）=====
            Optional<MembershipLevel> starterOpt = membershipLevelRepository.findByName("starter");
            if (starterOpt.isEmpty()) {
                logger.info("检测到数据库缺少 starter 等级，开始执行迁移...");
                migrateToFourLevels();
            } else {
                logger.info("会员等级数据已存在（含 starter），跳过初始化");
            }
        }
    }

    /**
     * 全新数据库：创建完整的 4 级会员体系
     */
    private void createAllLevels() {
        // free: 免费会员（新用户注册默认等级，无价格、无积分）
        MembershipLevel free = new MembershipLevel();
        free.setName("free");
        free.setDisplayName("免费会员");
        free.setPrice(0.0);
        free.setDurationDays(0);
        free.setPointsBonus(0);
        free.setDescription("免费会员（新用户注册默认）");
        free.setIsActive(true);
        free.setCreatedAt(LocalDateTime.now());
        free.setUpdatedAt(LocalDateTime.now());
        membershipLevelRepository.save(free);

        // starter: 入门会员（最低付费等级）
        MembershipLevel starter = new MembershipLevel();
        starter.setName("starter");
        starter.setDisplayName("入门会员");
        starter.setPrice(99.0);
        starter.setDurationDays(365);
        starter.setPointsBonus(1000);
        starter.setDescription("入门会员 - 每年1000积分");
        starter.setIsActive(true);
        starter.setCreatedAt(LocalDateTime.now());
        starter.setUpdatedAt(LocalDateTime.now());
        membershipLevelRepository.save(starter);

        MembershipLevel standard = new MembershipLevel();
        standard.setName("standard");
        standard.setDisplayName("标准会员");
        standard.setPrice(298.0);
        standard.setDurationDays(365);
        standard.setPointsBonus(6000);
        standard.setDescription("标准会员 - 每年6000积分");
        standard.setIsActive(true);
        standard.setCreatedAt(LocalDateTime.now());
        standard.setUpdatedAt(LocalDateTime.now());
        membershipLevelRepository.save(standard);

        MembershipLevel professional = new MembershipLevel();
        professional.setName("professional");
        professional.setDisplayName("专业版");
        professional.setPrice(398.0);
        professional.setDurationDays(365);
        professional.setPointsBonus(12000);
        professional.setDescription("专业会员 - 每年12000积分");
        professional.setIsActive(true);
        professional.setCreatedAt(LocalDateTime.now());
        professional.setUpdatedAt(LocalDateTime.now());
        membershipLevelRepository.save(professional);
    }

    /**
     * 从旧的 3 级体系迁移到新的 4 级体系：
     * 1. 从现有 free 等级复制价格和积分创建 starter
     * 2. 将已付费且当前为 free 的用户迁移到 starter
     * 3. 将 free 等级归零（price=0, points=0）
     */
    private void migrateToFourLevels() {
        Optional<MembershipLevel> freeOpt = membershipLevelRepository.findByName("free");
        if (freeOpt.isEmpty()) {
            logger.error("❌ 迁移失败：数据库中找不到 free 等级");
            return;
        }

        MembershipLevel freeLevel = freeOpt.get();

        // 第一步：创建 starter 等级，复制 free 的价格和积分
        Double oldFreePrice = freeLevel.getPrice();
        int oldFreePoints = freeLevel.getPointsBonus();

        MembershipLevel starter = new MembershipLevel();
        starter.setName("starter");
        starter.setDisplayName("入门会员");
        starter.setPrice(oldFreePrice != null && oldFreePrice > 0 ? oldFreePrice : 99.0);
        starter.setDurationDays(freeLevel.getDurationDays() > 0 ? freeLevel.getDurationDays() : 365);
        starter.setPointsBonus(oldFreePoints > 0 ? oldFreePoints : 1000);
        starter.setDescription("入门会员 - 每年" + starter.getPointsBonus() + "积分");
        starter.setIsActive(true);
        starter.setCreatedAt(LocalDateTime.now());
        starter.setUpdatedAt(LocalDateTime.now());
        membershipLevelRepository.save(starter);
        logger.info("✅ 已创建 starter 等级: price={}, points={}", starter.getPrice(), starter.getPointsBonus());

        // 第二步：将已付费用户从 free 迁移到 starter
        int migratedCount = 0;
        try {
            Long freeLevelId = freeLevel.getId();
            Long starterLevelId = starter.getId();

            // 查找所有当前为 free 等级的活跃会员
            List<UserMembership> freeMemberships = userMembershipRepository.findAll().stream()
                .filter(m -> "ACTIVE".equals(m.getStatus()) && freeLevelId.equals(m.getMembershipLevelId()))
                .toList();

            for (UserMembership membership : freeMemberships) {
                // 检查该用户是否有成功的支付记录
                BigDecimal totalPaid = paymentRepository.sumAmountByUserIdAndStatus(
                    membership.getUserId(), PaymentStatus.SUCCESS);
                
                if (totalPaid != null && totalPaid.compareTo(BigDecimal.ZERO) > 0) {
                    // 有支付记录，迁移到 starter
                    membership.setMembershipLevelId(starterLevelId);
                    membership.setUpdatedAt(LocalDateTime.now());
                    userMembershipRepository.save(membership);
                    migratedCount++;
                }
            }
            logger.info("✅ 已将 {} 个已付费用户从 free 迁移到 starter", migratedCount);
        } catch (Exception e) {
            logger.warn("⚠️ 用户迁移过程中出现异常（不影响等级创建）: {}", e.getMessage());
        }

        // 第三步：将 free 等级归零
        freeLevel.setPrice(0.0);
        freeLevel.setPointsBonus(0);
        freeLevel.setDisplayName("免费会员");
        freeLevel.setDescription("免费会员（新用户注册默认）");
        freeLevel.setUpdatedAt(LocalDateTime.now());
        membershipLevelRepository.save(freeLevel);
        logger.info("✅ 已将 free 等级归零: price=0, points=0, displayName=免费会员");

        logger.info("✅ 迁移完成！4 级会员体系: free(免费会员) → starter(入门会员) → standard(标准会员) → professional(专业版)");
    }
}
