package com.example.demo.service;

import com.example.demo.config.DynamicApiConfig;
import com.example.demo.model.SystemSettings;
import com.example.demo.repository.SystemSettingsRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SystemSettingsService {

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

    private final SystemSettingsRepository repository;
    
    @Autowired
    private DynamicApiConfig dynamicApiConfig;

    public SystemSettingsService(SystemSettingsRepository repository) {
        this.repository = repository;
    }

    /**
     * 获取唯一的系统设置；若不存在则初始化默认值。
     * 注意：套餐价格已移至 membership_levels 表管理
     */
    @Transactional
    public SystemSettings getOrCreate() {
        List<SystemSettings> all = repository.findAll();
        if (all.isEmpty()) {
            SystemSettings defaults = new SystemSettings();
            defaults.setPointsPerGeneration(1); // 默认每次消耗 1 点
            defaults.setSiteName("AIGC Demo");
            defaults.setSiteSubtitle("现代化的Spring Boot应用演示");
            defaults.setRegistrationOpen(true);
            defaults.setMaintenanceMode(false);
            defaults.setEnableAlipay(true);
            defaults.setEnablePaypal(true);
            defaults.setContactEmail("support@example.com");
            defaults.setPromptOptimizationModel("gpt-5.1-thinking");
            defaults.setStoryboardSystemPrompt("");
            defaults.setTextToVideoPoints(30);
            defaults.setImageToVideoPoints(30);
            defaults.setStoryboardImagePoints(30);
            defaults.setStoryboardVideoPoints(30);
            SystemSettings saved = repository.save(defaults);
            logger.info("Initialized default SystemSettings: points={}",
                    saved.getPointsPerGeneration());
            return saved;
        }
        return all.get(0);
    }

    @Transactional
    public SystemSettings update(SystemSettings updated) {
        // 如果 API Key 为空，保留原来的值
        if (updated.getAiApiKey() == null || updated.getAiApiKey().trim().isEmpty()) {
            SystemSettings existing = getOrCreate();
            updated.setAiApiKey(existing.getAiApiKey());
        }
        
        // 记录保存前的tokenExpireHours值
        logger.info("保存前 tokenExpireHours: {}", updated.getTokenExpireHours());
        
        // 保存更新
        SystemSettings saved = repository.save(updated);
        logger.info("系统设置保存成功: id={}, tokenExpireHours={}", saved.getId(), saved.getTokenExpireHours());
        
        // 刷新运行时配置
        if (saved.getAiApiKey() != null && !saved.getAiApiKey().isEmpty()) {
            dynamicApiConfig.updateApiKey(saved.getAiApiKey());
            dynamicApiConfig.updateImageApiKey(saved.getAiApiKey());
        }
        if (saved.getAiApiBaseUrl() != null && !saved.getAiApiBaseUrl().isEmpty()) {
            dynamicApiConfig.updateApiBaseUrl(saved.getAiApiBaseUrl());
            dynamicApiConfig.updateImageApiBaseUrl(saved.getAiApiBaseUrl());
        }
        
        return saved;
    }
}


