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
}

// AdminInquiryFilter 咨询列表筛选
type AdminInquiryFilter struct {
	Keyword   string
	Status    int // -1 表示全部
	StartDate string
	EndDate   string
}

// GetInquiriesAdmin 获取咨询列表 (Admin，分页)
func GetInquiriesAdmin(page, pageSize int, filter AdminInquiryFilter) ([]models.Inquiry, int64, error) {
	offset := (page - 1) * pageSize
	var inquiries []models.Inquiry
	var total int64

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

	if filter.Keyword != "" {
		like := "%" + filter.Keyword + "%"
		query = query.Where("(name LIKE ? OR company LIKE ? OR contact_value LIKE ? OR description LIKE ?)",
			like, like, like, like)
	}
	if filter.Status >= 0 {
		query = query.Where("status = ?", filter.Status)
	}
	if filter.StartDate != "" {
		if ts, err := parseInquiryDateStart(filter.StartDate); err == nil {
			query = query.Where("created_at >= ?", ts)
		}
	}
	if filter.EndDate != "" {
		if ts, err := parseInquiryDateEnd(filter.EndDate); err == nil {
			query = query.Where("created_at <= ?", ts)
		}
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	err := query.Order("created_at DESC").
		Limit(pageSize).
		Offset(offset).
		Find(&inquiries).Error
	return inquiries, total, err
}

func parseInquiryDateStart(dateStr string) (int64, error) {
	t, err := time.ParseInLocation("2006-01-02", dateStr, time.Local)
	if err != nil {
		return 0, err
	}
	return t.Unix(), nil
}

func parseInquiryDateEnd(dateStr string) (int64, error) {
	t, err := time.ParseInLocation("2006-01-02", dateStr, time.Local)
	if err != nil {
		return 0, err
	}
	return t.Add(24*time.Hour - time.Second).Unix(), nil
}

// GetInquiries 获取咨询列表 (Admin) — 兼容旧调用
func GetInquiries() ([]models.Inquiry, error) {
	list, _, err := GetInquiriesAdmin(1, 10000, AdminInquiryFilter{Status: -1})
	return list, err
}

// 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
}
