package repositories

import (
	"log"
	"time"

	"github.com/niangaodev/art-code/config"
	"github.com/niangaodev/art-code/models"
	"gorm.io/gorm"
)

// GetSettings 获取所有系统配置
func GetSettings() ([]models.Setting, error) {
	var settings []models.Setting
	err := config.DB.Model(&models.Setting{}).
		Where("deleted_at = ?", 0).
		Order("key_name").
		Find(&settings).Error
	if err != nil {
		log.Printf("Error querying settings: %v", err)
		return nil, err
	}
	return settings, nil
}

// GetSettingByKey 根据键名获取系统配置
func GetSettingByKey(keyName string) (*models.Setting, error) {
	var setting models.Setting
	err := config.DB.Model(&models.Setting{}).
		Where("key_name = ? AND deleted_at = ?", keyName, 0).
		First(&setting).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting setting by key: %v", err)
		return nil, err
	}
	return &setting, nil
}

// UpdateSetting 更新系统配置
func UpdateSetting(setting *models.Setting) error {
	err := config.DB.Model(&models.Setting{}).
		Where("key_name = ? AND deleted_at = ?", setting.KeyName, 0).
		Updates(map[string]interface{}{
			"value":       setting.Value,
			"description": setting.Description,
			"updated_at":  time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating setting: %v", err)
		return err
	}
	return nil
}

// CreateSetting 创建系统配置
func CreateSetting(setting *models.Setting) error {
	err := config.DB.Create(setting).Error
	if err != nil {
		log.Printf("Error creating setting: %v", err)
		return err
	}
	return nil
}

// DeleteSetting 删除系统配置 (Soft Delete)
func DeleteSetting(keyName string) error {
	err := config.DB.Model(&models.Setting{}).
		Where("key_name = ?", keyName).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting setting: %v", err)
		return err
	}
	return nil
}

// BuildSettingResponse 构建系统配置响应
func BuildSettingResponse(setting *models.Setting) *models.SettingResponse {
	return &models.SettingResponse{
		ID:          setting.ID,
		KeyName:     setting.KeyName,
		Value:       setting.Value,
		Description: setting.Description,
		CreatedAt:   time.Unix(setting.CreatedAt, 0).Format("2006-01-02 15:04:05"),
		UpdatedAt:   time.Unix(setting.UpdatedAt, 0).Format("2006-01-02 15:04:05"),
	}
}

// GetAllSettings 获取所有系统配置 (Map format for easier consumption)
func GetAllSettings() (map[string]string, error) {
	settings, err := GetSettings()
	if err != nil {
		return nil, err
	}

	result := make(map[string]string)
	for _, s := range settings {
		result[s.KeyName] = s.Value
	}
	return result, nil
}

// UpdateSettings 批量更新系统配置
func UpdateSettings(settings map[string]string) error {
	return config.DB.Transaction(func(tx *gorm.DB) error {
		now := time.Now().Unix()
		for key, value := range settings {
			err := tx.Model(&models.Setting{}).
				Where("key_name = ? AND deleted_at = ?", key, 0).
				Updates(map[string]interface{}{
					"value":      value,
					"updated_at": now,
				}).Error
			if err != nil {
				log.Printf("Error updating setting %s: %v", key, err)
				return err
			}
		}
		return nil
	})
}
