package com.example.demo.service;

import com.example.demo.model.SystemSettings;
import com.example.demo.repository.SystemSettingsRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

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

    /**
     * 获取唯一的系统设置；若不存在则初始化默认值。
     */
    @Transactional
    public SystemSettings getOrCreate() {
        List<SystemSettings> all = repository.findAll();
        if (all.isEmpty()) {
            SystemSettings defaults = new SystemSettings();
            defaults.setStandardPriceCny(9);    // 默认标准版 9 元
            defaults.setProPriceCny(29);        // 默认专业版 29 元
            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");
            SystemSettings saved = repository.save(defaults);
            logger.info("Initialized default SystemSettings: std={}, pro={}, points={}",
                    saved.getStandardPriceCny(), saved.getProPriceCny(), saved.getPointsPerGeneration());
            return saved;
        }
        return all.get(0);
    }

    @Transactional
    public SystemSettings update(SystemSettings updated) {
        // 确保只有一条记录
        SystemSettings current = getOrCreate();
        current.setStandardPriceCny(updated.getStandardPriceCny());
        current.setProPriceCny(updated.getProPriceCny());
        current.setPointsPerGeneration(updated.getPointsPerGeneration());
        current.setSiteName(updated.getSiteName());
        current.setSiteSubtitle(updated.getSiteSubtitle());
        current.setRegistrationOpen(updated.getRegistrationOpen());
        current.setMaintenanceMode(updated.getMaintenanceMode());
        current.setEnableAlipay(updated.getEnableAlipay());
        current.setEnablePaypal(updated.getEnablePaypal());
        current.setContactEmail(updated.getContactEmail());
        return repository.save(current);
    }
}


