package repository

import (
	"strings"

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

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

func (s *Store) ListAppSplashScreens(options AppSplashScreenListOptions) ([]model.AppSplashScreen, error) {
	var items []model.AppSplashScreen
	// 后台列表始终先按 app_code 隔离，再叠加可选筛选；区域 0 和国家空值在管理端表示全量配置，不需要额外匹配。
	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) + "%"
		// 关键字只查人工可识别的字段，避免把封面 URL 这类长字段带进模糊查询拖慢列表。
		query = query.Where("(description LIKE ? OR param LIKE ? OR country_code LIKE ?)", like, like, like)
	}
	err := query.Order("sort_order DESC, id DESC").Find(&items).Error
	return items, err
}

func (s *Store) ExpireAppSplashScreens(appCode string, nowMs int64) error {
	appCode = strings.TrimSpace(appCode)
	if appCode == "" || nowMs <= 0 {
		return nil
	}
	// 过期回收只处理 active 且已到结束时间的记录，手动关闭和历史 expired 状态保持原样，方便后台审计。
	return s.db.Model(&model.AppSplashScreen{}).
		Where("app_code = ? AND status = ? AND ends_at_ms > 0 AND ends_at_ms <= ?", appCode, "active", nowMs).
		Updates(map[string]any{
			"status":        "expired",
			"updated_at_ms": nowMs,
		}).Error
}

func (s *Store) GetAppSplashScreen(appCode string, id uint) (model.AppSplashScreen, error) {
	var item model.AppSplashScreen
	// app_code 和 id 共同限定记录，避免多 App 后台误编辑其他租户配置。
	err := s.db.Where("app_code = ? AND id = ?", strings.TrimSpace(appCode), id).First(&item).Error
	return item, err
}

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

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

func (s *Store) DeleteAppSplashScreen(appCode string, id uint) error {
	// 删除沿用硬删除语义，和 Banner 配置保持一致；操作日志在 handler 层记录。
	return s.db.Where("app_code = ? AND id = ?", strings.TrimSpace(appCode), id).Delete(&model.AppSplashScreen{}).Error
}
