package service

import (
	"fmt"
	"verification-platform-backend/internal/database"
	"verification-platform-backend/internal/model"

	"gorm.io/gorm/clause"
)

type SettingService struct{}

func NewSettingService() *SettingService {
	return &SettingService{}
}

func (s *SettingService) GetSettings() (map[string]interface{}, error) {
	var settings []model.Setting
	if err := database.DB.Find(&settings).Error; err != nil {
		return nil, err
	}

	result := make(map[string]interface{})
	for _, setting := range settings {
		if _, ok := result[setting.Category]; !ok {
			result[setting.Category] = make(map[string]interface{})
		}
		result[setting.Category].(map[string]interface{})[setting.Key] = setting.Value
	}

	fmt.Println("========================================")
	fmt.Println("GetSettings 返回的数据:")
	for cat, data := range result {
		fmt.Printf("  分类: %s\n", cat)
		if dataMap, ok := data.(map[string]interface{}); ok {
			for k, v := range dataMap {
				fmt.Printf("    %s: %v\n", k, v)
			}
		}
	}
	fmt.Println("========================================")

	return result, nil
}

func (s *SettingService) GetSettingsByCategory(category string) (map[string]interface{}, error) {
	var settings []model.Setting
	if err := database.DB.Where("category = ?", category).Find(&settings).Error; err != nil {
		return nil, err
	}

	result := make(map[string]interface{})
	for _, setting := range settings {
		result[setting.Key] = setting.Value
	}

	return result, nil
}

func (s *SettingService) UpdateSettings(category string, data map[string]interface{}) error {
	fmt.Println("========================================")
	fmt.Printf("UpdateSettings 被调用: category=%s\n", category)
	for key, value := range data {
		var strValue string
		switch v := value.(type) {
		case string:
			strValue = v
		case bool:
			if v {
				strValue = "true"
			} else {
				strValue = "false"
			}
		case int:
			strValue = fmt.Sprintf("%d", v)
		case int64:
			strValue = fmt.Sprintf("%d", v)
		case float64:
			strValue = fmt.Sprintf("%.0f", v)
		case float32:
			strValue = fmt.Sprintf("%.0f", v)
		default:
			fmt.Printf("  跳过: %s (类型: %T, 值: %v)\n", key, value, value)
			continue
		}

		fmt.Printf("  保存: %s = %s\n", key, strValue)

		setting := model.Setting{
			Category: category,
			Key:      key,
			Value:    strValue,
		}

		if err := database.DB.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "key"}},
			DoUpdates: clause.AssignmentColumns([]string{"value", "category", "updated_at"}),
		}).Create(&setting).Error; err != nil {
			fmt.Printf("  保存失败: %v\n", err)
			return err
		}
	}
	fmt.Println("========================================")

	return nil
}

func (s *SettingService) GetSetting(category, key string) (string, error) {
	var setting model.Setting
	if err := database.DB.Where("category = ? AND key = ?", category, key).First(&setting).Error; err != nil {
		return "", err
	}
	return setting.Value, nil
}

func (s *SettingService) SetSetting(category, key, value string) error {
	setting := model.Setting{
		Category: category,
		Key:      key,
		Value:    value,
	}

	return database.DB.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "key"}},
		DoUpdates: clause.AssignmentColumns([]string{"value", "category", "updated_at"}),
	}).Create(&setting).Error
}
