package repositories

import (
	"log"
	"time"

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

// CreateInquiry 创建咨询
func CreateInquiry(inquiry *models.Inquiry) error {
	err := config.DB.Create(inquiry).Error
	if err != nil {
		log.Printf("Error creating inquiry: %v", err)
		return err
	}
	return nil
}

// GetInquiries 获取咨询列表 (Admin)
func GetInquiries() ([]models.Inquiry, error) {
	var inquiries []models.Inquiry
	err := config.DB.Model(&models.Inquiry{}).
		Where("deleted_at = ?", 0).
		Order("created_at DESC").
		Find(&inquiries).Error
	if err != nil {
		return nil, err
	}
	return inquiries, nil
}

// GetInquiryCount 获取咨询总数
func GetInquiryCount() (int64, error) {
	var count int64
	err := config.DB.Model(&models.Inquiry{}).
		Where("deleted_at = ?", 0).
		Count(&count).Error
	return count, err
}

// GetEmailSuffixes 获取活跃的邮箱后缀
func GetEmailSuffixes() ([]models.EmailSuffix, error) {
	var suffixes []models.EmailSuffix
	err := config.DB.Model(&models.EmailSuffix{}).
		Where("is_active = ? AND deleted_at = ?", true, 0).
		Order("sort_order ASC").
		Find(&suffixes).Error
	return suffixes, err
}

// AdminGetEmailSuffixes 获取所有邮箱后缀 (Admin)
func AdminGetEmailSuffixes() ([]models.EmailSuffix, error) {
	var suffixes []models.EmailSuffix
	err := config.DB.Model(&models.EmailSuffix{}).
		Where("deleted_at = ?", 0).
		Order("sort_order ASC").
		Find(&suffixes).Error
	return suffixes, err
}

// CreateEmailSuffix 创建邮箱后缀
func CreateEmailSuffix(suffix *models.EmailSuffix) error {
	return config.DB.Create(suffix).Error
}

// UpdateEmailSuffix 更新邮箱后缀
func UpdateEmailSuffix(suffix *models.EmailSuffix) error {
	return config.DB.Model(&models.EmailSuffix{}).
		Where("id = ? AND deleted_at = ?", suffix.ID, 0).
		Updates(map[string]interface{}{
			"suffix":     suffix.Suffix,
			"is_active":  suffix.IsActive,
			"sort_order": suffix.SortOrder,
			"updated_at": time.Now().Unix(),
		}).Error
}

// DeleteEmailSuffix 删除邮箱后缀 (Soft Delete)
func DeleteEmailSuffix(id uint) error {
	return config.DB.Model(&models.EmailSuffix{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
}

// UpdateInquiryStatus 更新咨询状态
func UpdateInquiryStatus(id uint, status int) error {
	return config.DB.Model(&models.Inquiry{}).
		Where("id = ? AND deleted_at = ?", id, 0).
		Updates(map[string]interface{}{
			"status":     status,
			"updated_at": time.Now().Unix(),
		}).Error
}
