package repositories

import (
	"log"
	"time"

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

// GetTestimonials 获取所有客户评价
func GetTestimonials() ([]models.Testimonial, error) {
	var testimonials []models.Testimonial
	err := config.DB.Model(&models.Testimonial{}).
		Where("deleted_at = ?", 0).
		Order("sort_order ASC, created_at DESC").
		Find(&testimonials).Error
	if err != nil {
		log.Printf("Error querying testimonials: %v", err)
		return nil, err
	}
	return testimonials, nil
}

// CreateTestimonial 创建客户评价
func CreateTestimonial(t *models.Testimonial) error {
	err := config.DB.Create(t).Error
	if err != nil {
		log.Printf("Error creating testimonial: %v", err)
		return err
	}
	return nil
}

// UpdateTestimonial 更新客户评价
func UpdateTestimonial(t *models.Testimonial) error {
	err := config.DB.Model(&models.Testimonial{}).
		Where("id = ?", t.ID).
		Updates(map[string]interface{}{
			"name":       t.Name,
			"role":       t.Role,
			"content":    t.Content,
			"avatar":     t.Avatar,
			"rating":     t.Rating,
			"sort_order": t.SortOrder,
			"updated_at": time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating testimonial: %v", err)
		return err
	}
	return nil
}

// DeleteTestimonial 删除客户评价
func DeleteTestimonial(id uint) error {
	err := config.DB.Model(&models.Testimonial{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting testimonial: %v", err)
		return err
	}
	return nil
}

// GetPartners 获取所有合作伙伴
func GetPartners() ([]models.Partner, error) {
	var partners []models.Partner
	err := config.DB.Model(&models.Partner{}).
		Where("deleted_at = ?", 0).
		Order("sort_order ASC, created_at DESC").
		Find(&partners).Error
	if err != nil {
		log.Printf("Error querying partners: %v", err)
		return nil, err
	}
	return partners, nil
}

// CreatePartner 创建合作伙伴
func CreatePartner(p *models.Partner) error {
	err := config.DB.Create(p).Error
	if err != nil {
		log.Printf("Error creating partner: %v", err)
		return err
	}
	return nil
}

// UpdatePartner 更新合作伙伴
func UpdatePartner(p *models.Partner) error {
	err := config.DB.Model(&models.Partner{}).
		Where("id = ?", p.ID).
		Updates(map[string]interface{}{
			"name":        p.Name,
			"logo":        p.Logo,
			"description": p.Description,
			"url":         p.URL,
			"sort_order":  p.SortOrder,
			"updated_at":  time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating partner: %v", err)
		return err
	}
	return nil
}

// DeletePartner 删除合作伙伴
func DeletePartner(id uint) error {
	err := config.DB.Model(&models.Partner{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting partner: %v", err)
		return err
	}
	return nil
}
