package plant

import (
	"sundynix-go/global"
	"sundynix-go/model/plant"
	"sundynix-go/model/plant/request"
)

type BannerService struct{}

func (s *BannerService) Create(req plant.Banner) error {
	return global.DB.Create(&req).Error
}

func (s *BannerService) Delete(id string) error {
	return global.DB.Where("id = ?", id).Delete(&plant.Banner{}).Error
}

func (s *BannerService) Update(req plant.Banner) error {
	return global.DB.Model(&plant.Banner{}).Where("id = ?", req.Id).Updates(map[string]interface{}{
		"title":      req.Title,
		"image_id":   req.ImageId,
		"sort":       req.Sort,
		"is_active":  req.IsActive,
		"target_url": req.TargetUrl,
	}).Error
}

func (s *BannerService) GetList(req request.BannerPageReq) (list interface{}, total int64, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.Current - 1)
	db := global.DB.Model(&plant.Banner{}).Preload("Image")
	if req.Title != "" {
		db = db.Where("title LIKE ?", "%"+req.Title+"%")
	}
	if req.IsActive != nil {
		db = db.Where("is_active = ?", *req.IsActive)
	}

	var banners []plant.Banner
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Order("sort asc, created_at desc").Limit(limit).Offset(offset).Find(&banners).Error
	return banners, total, err
}

func (s *BannerService) GetActiveList() ([]plant.Banner, error) {
	var banners []plant.Banner
	err := global.DB.Model(&plant.Banner{}).Preload("Image").
		Where("is_active = 1").
		Order("sort asc, created_at desc").
		Find(&banners).Error
	return banners, err
}
