package repository

import (
	"strings"
	"time"

	"hyapp-admin-server/internal/model"

	"gorm.io/gorm/clause"
)

type AppVersionListOptions struct {
	AppCode  string
	Platform string
	Keyword  string
}

func (s *Store) ListAppConfigs(group string) ([]model.AppConfig, error) {
	var items []model.AppConfig
	err := s.db.Where("`group` = ?", strings.TrimSpace(group)).Order("`key` ASC").Find(&items).Error
	return items, err
}

func (s *Store) UpsertAppConfigs(items []model.AppConfig) error {
	if len(items) == 0 {
		return nil
	}

	nowMS := time.Now().UTC().UnixMilli()
	for index := range items {
		items[index].Group = strings.TrimSpace(items[index].Group)
		items[index].Key = strings.TrimSpace(items[index].Key)
		items[index].UpdatedAtMS = nowMS
		if items[index].CreatedAtMS == 0 {
			items[index].CreatedAtMS = nowMS
		}
	}

	return s.db.Clauses(clause.OnConflict{
		Columns: []clause.Column{
			{Name: "group"},
			{Name: "key"},
		},
		DoUpdates: clause.AssignmentColumns([]string{"value", "description", "updated_at_ms"}),
	}).Create(&items).Error
}

func (s *Store) ListAppVersions(options AppVersionListOptions) ([]model.AppVersion, error) {
	db := s.db.Where("app_code = ?", strings.TrimSpace(options.AppCode))
	if platform := strings.TrimSpace(options.Platform); platform != "" {
		db = db.Where("platform = ?", platform)
	}
	if keyword := strings.TrimSpace(options.Keyword); keyword != "" {
		like := "%" + keyword + "%"
		db = db.Where("version LIKE ? OR download_url LIKE ? OR description LIKE ?", like, like, like)
	}

	var items []model.AppVersion
	err := db.Order("platform ASC, build_number DESC, id DESC").Find(&items).Error
	return items, err
}

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

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

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

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