package repositories

import (
	"log"
	"time"

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

// CreateAttachment 创建附件记录
func CreateAttachment(attachment *models.Attachment) error {
	err := config.DB.Create(attachment).Error
	if err != nil {
		log.Printf("Error creating attachment: %v", err)
		return err
	}
	return nil
}

// GetAttachments 获取附件列表（分页）
func GetAttachments(page, pageSize int, categoryID *uint, fileType, keyword string) ([]models.Attachment, int64, error) {
	offset := (page - 1) * pageSize

	var attachments []models.Attachment
	var total int64

	query := config.DB.Model(&models.Attachment{}).
		Preload("Category").
		Where("deleted_at = ?", 0)

	if categoryID != nil && *categoryID > 0 {
		query = query.Where("category_id = ?", *categoryID)
	}

	if fileType != "" {
		query = query.Where("file_type = ?", fileType)
	}

	if keyword != "" {
		like := "%" + keyword + "%"
		query = query.Where("original_name LIKE ?", like)
	}

	// Count total
	err := query.Count(&total).Error
	if err != nil {
		log.Printf("Error counting attachments: %v", err)
		return nil, 0, err
	}

	// Get attachments
	err = query.Order("created_at DESC").
		Limit(pageSize).
		Offset(offset).
		Find(&attachments).Error

	if err != nil {
		log.Printf("Error querying attachments: %v", err)
		return nil, 0, err
	}

	return attachments, total, nil
}

// GetAttachmentByID 根据ID获取附件
func GetAttachmentByID(id uint) (*models.Attachment, error) {
	var attachment models.Attachment
	err := config.DB.Model(&models.Attachment{}).
		Preload("Category").
		Where("id = ? AND deleted_at = ?", id, 0).
		First(&attachment).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting attachment by ID: %v", err)
		return nil, err
	}

	return &attachment, nil
}

// UpdateAttachment 更新附件
func UpdateAttachment(attachment *models.Attachment) error {
	updateData := map[string]interface{}{
		"updated_at": time.Now().Unix(),
	}

	if attachment.CategoryID != nil {
		updateData["category_id"] = attachment.CategoryID
	} else {
		// 如果CategoryID为nil，设置为NULL
		updateData["category_id"] = nil
	}

	err := config.DB.Model(&models.Attachment{}).
		Where("id = ? AND deleted_at = ?", attachment.ID, 0).
		Updates(updateData).Error

	if err != nil {
		log.Printf("Error updating attachment: %v", err)
		return err
	}
	return nil
}

// DeleteAttachment 删除附件（软删除）
func DeleteAttachment(id uint) error {
	err := config.DB.Model(&models.Attachment{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting attachment: %v", err)
		return err
	}
	return nil
}

// CreateAttachmentCategory 创建附件分类
func CreateAttachmentCategory(category *models.AttachmentCategory) error {
	err := config.DB.Create(category).Error
	if err != nil {
		log.Printf("Error creating attachment category: %v", err)
		return err
	}
	return nil
}

// GetAttachmentCategories 获取所有附件分类
func GetAttachmentCategories() ([]models.AttachmentCategory, error) {
	var categories []models.AttachmentCategory
	err := config.DB.Model(&models.AttachmentCategory{}).
		Where("deleted_at = ?", 0).
		Order("sort_order ASC, created_at DESC").
		Find(&categories).Error

	if err != nil {
		log.Printf("Error querying attachment categories: %v", err)
		return nil, err
	}

	return categories, nil
}

// UpdateAttachmentCategory 更新附件分类
func UpdateAttachmentCategory(category *models.AttachmentCategory) error {
	err := config.DB.Model(&models.AttachmentCategory{}).
		Where("id = ? AND deleted_at = ?", category.ID, 0).
		Updates(map[string]interface{}{
			"name":        category.Name,
			"description": category.Description,
			"sort_order":  category.SortOrder,
			"updated_at":  time.Now().Unix(),
		}).Error

	if err != nil {
		log.Printf("Error updating attachment category: %v", err)
		return err
	}
	return nil
}

// DeleteAttachmentCategory 删除附件分类（软删除）
func DeleteAttachmentCategory(id uint) error {
	err := config.DB.Model(&models.AttachmentCategory{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting attachment category: %v", err)
		return err
	}
	return nil
}

// CreateOSSConfig 创建OSS配置
func CreateOSSConfig(ossConfig *models.OSSConfig) error {
	err := config.DB.Create(ossConfig).Error
	if err != nil {
		log.Printf("Error creating OSS config: %v", err)
		return err
	}
	return nil
}

// GetOSSConfigs 获取所有OSS配置
func GetOSSConfigs() ([]models.OSSConfig, error) {
	var configs []models.OSSConfig
	err := config.DB.Model(&models.OSSConfig{}).
		Where("deleted_at = ?", 0).
		Order("created_at DESC").
		Find(&configs).Error

	if err != nil {
		log.Printf("Error querying OSS configs: %v", err)
		return nil, err
	}

	return configs, nil
}

// GetOSSConfigByID 根据ID获取OSS配置
func GetOSSConfigByID(id uint) (*models.OSSConfig, error) {
	var ossConfig models.OSSConfig
	err := config.DB.Model(&models.OSSConfig{}).
		Where("id = ? AND deleted_at = ?", id, 0).
		First(&ossConfig).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting OSS config by ID: %v", err)
		return nil, err
	}

	return &ossConfig, nil
}

// GetActiveOSSConfig 获取启用的OSS配置
func GetActiveOSSConfig(storageType string) (*models.OSSConfig, error) {
	var ossConfig models.OSSConfig
	query := config.DB.Model(&models.OSSConfig{}).
		Where("deleted_at = ? AND is_active = ?", 0, 1)

	if storageType != "" {
		query = query.Where("storage_type = ?", storageType)
	}

	err := query.First(&ossConfig).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting active OSS config: %v", err)
		return nil, err
	}

	return &ossConfig, nil
}

// GetDefaultLocalOSSConfig 获取默认本地存储配置
func GetDefaultLocalOSSConfig() (*models.OSSConfig, error) {
	var ossConfig models.OSSConfig
	err := config.DB.Model(&models.OSSConfig{}).
		Where("deleted_at = ? AND name = ? AND storage_type = ?", 0, "本地存储", "local").
		First(&ossConfig).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting default local OSS config: %v", err)
		return nil, err
	}

	return &ossConfig, nil
}

// UpdateOSSConfig 更新OSS配置
func UpdateOSSConfig(ossConfig *models.OSSConfig) error {
	err := config.DB.Model(&models.OSSConfig{}).
		Where("id = ? AND deleted_at = ?", ossConfig.ID, 0).
		Updates(map[string]interface{}{
			"name":         ossConfig.Name,
			"storage_type": ossConfig.StorageType,
			"access_key":   ossConfig.AccessKey,
			"secret_key":   ossConfig.SecretKey,
			"bucket":       ossConfig.Bucket,
			"region":       ossConfig.Region,
			"domain":       ossConfig.Domain,
			"is_active":    ossConfig.IsActive,
			"updated_at":   time.Now().Unix(),
		}).Error

	if err != nil {
		log.Printf("Error updating OSS config: %v", err)
		return err
	}
	return nil
}

// DeleteOSSConfig 删除OSS配置（软删除）
func DeleteOSSConfig(id uint) error {
	err := config.DB.Model(&models.OSSConfig{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting OSS config: %v", err)
		return err
	}
	return nil
}
