package repository

import (
	"strings"

	"hyapp-admin-server/internal/model"
)

type AppBannerListOptions struct {
	AppCode  string
	Keyword  string
	Status   string
	Platform string
	RegionID int64
	Country  string
}

func (s *Store) ListAppBanners(options AppBannerListOptions) ([]model.AppBanner, error) {
	var items []model.AppBanner
	query := s.db.Where("app_code = ?", strings.TrimSpace(options.AppCode))
	if options.Status != "" {
		query = query.Where("status = ?", strings.TrimSpace(options.Status))
	}
	if options.Platform != "" {
		query = query.Where("platform = ?", strings.TrimSpace(options.Platform))
	}
	if options.RegionID > 0 {
		query = query.Where("region_id = ?", options.RegionID)
	}
	if options.Country != "" {
		query = query.Where("country_code = ?", strings.TrimSpace(options.Country))
	}
	if options.Keyword != "" {
		like := "%" + strings.TrimSpace(options.Keyword) + "%"
		query = query.Where("(description LIKE ? OR param LIKE ? OR country_code LIKE ?)", like, like, like)
	}
	err := query.Order("sort_order ASC, id DESC").Find(&items).Error
	return items, err
}

func (s *Store) GetAppBanner(appCode string, id uint) (model.AppBanner, error) {
	var item model.AppBanner
	err := s.db.Where("app_code = ? AND id = ?", strings.TrimSpace(appCode), id).First(&item).Error
	return item, err
}

func (s *Store) CreateAppBanner(item *model.AppBanner) error {
	return s.db.Create(item).Error
}

func (s *Store) UpdateAppBanner(item *model.AppBanner) error {
	return s.db.Save(item).Error
}

func (s *Store) DeleteAppBanner(appCode string, id uint) error {
	return s.db.Where("app_code = ? AND id = ?", strings.TrimSpace(appCode), id).Delete(&model.AppBanner{}).Error
}
