package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

import com.example.demo.model.SystemSettings;
import com.example.demo.model.MembershipLevel;
import com.example.demo.repository.UserRepository;
import com.example.demo.repository.MembershipLevelRepository;
import com.example.demo.service.SystemSettingsService;

@RestController
@RequestMapping("/api/public")
public class PublicApiController {

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

    private final UserRepository userRepository;
    private final SystemSettingsService systemSettingsService;
    private final MembershipLevelRepository membershipLevelRepository;

    public PublicApiController(UserRepository userRepository, SystemSettingsService systemSettingsService,
                               MembershipLevelRepository membershipLevelRepository) {
        this.userRepository = userRepository;
        this.systemSettingsService = systemSettingsService;
        this.membershipLevelRepository = membershipLevelRepository;
    }
    
    /**
     * 获取公开的系统配置（套餐价格等）
     * 无需登录即可访问
     */
    @GetMapping("/config")
    public Map<String, Object> getPublicConfig() {
        Map<String, Object> config = new HashMap<>();
        SystemSettings settings = systemSettingsService.getOrCreate();
        
        // 从membership_levels表读取价格（容错：缺少某个等级不影响其他等级）
        Optional<MembershipLevel> starterOpt = membershipLevelRepository.findByName("starter");
        Optional<MembershipLevel> standardOpt = membershipLevelRepository.findByName("standard");
        Optional<MembershipLevel> proOpt = membershipLevelRepository.findByName("professional");
        
        if (starterOpt.isEmpty()) {
            logger.warn("数据库中缺少starter会员等级配置，请检查V15迁移是否执行");
        }
        if (standardOpt.isEmpty()) {
            logger.warn("数据库中缺少standard会员等级配置");
        }
        if (proOpt.isEmpty()) {
            logger.warn("数据库中缺少professional会员等级配置");
        }
        
        // 套餐价格配置（从membership_levels表读取）
        config.put("starterPriceCny", starterOpt.map(MembershipLevel::getPrice).orElse(0.0));
        config.put("starterPoints", starterOpt.map(MembershipLevel::getPointsBonus).orElse(0));
        config.put("standardPriceCny", standardOpt.map(MembershipLevel::getPrice).orElse(0.0));
        config.put("standardPoints", standardOpt.map(MembershipLevel::getPointsBonus).orElse(0));
        config.put("proPriceCny", proOpt.map(MembershipLevel::getPrice).orElse(0.0));
        config.put("proPoints", proOpt.map(MembershipLevel::getPointsBonus).orElse(0));
        config.put("pointsPerGeneration", settings.getPointsPerGeneration());
        
        // 支付渠道开关
        config.put("enableAlipay", settings.getEnableAlipay());
        config.put("enablePaypal", settings.getEnablePaypal());
        
        // 返回所有会员等级列表
        List<MembershipLevel> levels = membershipLevelRepository.findAll();
        config.put("membershipLevels", levels.stream().map(level -> {
            Map<String, Object> levelMap = new HashMap<>();
            levelMap.put("id", level.getId());
            levelMap.put("name", level.getName());
            levelMap.put("displayName", level.getDisplayName());
            levelMap.put("price", level.getPrice());
            levelMap.put("pointsBonus", level.getPointsBonus());
            levelMap.put("durationDays", level.getDurationDays());
            levelMap.put("description", level.getDescription());
            return levelMap;
        }).collect(Collectors.toList()));
        
        return config;
    }

    @GetMapping("/users/exists/username")
    public Map<String, Boolean> existsUsername(@RequestParam("value") String username) {
        return Map.of("exists", userRepository.existsByUsername(username));
    }

    @GetMapping("/users/exists/email")
    public Map<String, Boolean> existsEmail(@RequestParam("value") String email) {
        return Map.of("exists", userRepository.existsByEmail(email));
    }
}
