package db

import (
	"gitlink.org.cn/cloudream/jcs-pub/client/types"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type PackageAccessStatDB struct {
	*DB
}

func (db *DB) PackageAccessStat() *PackageAccessStatDB {
	return &PackageAccessStatDB{db}
}

func (*PackageAccessStatDB) Get(ctx SQLContext, pkgID types.PackageID, spaceID types.UserSpaceID) (types.PackageAccessStat, error) {
	var ret types.PackageAccessStat
	err := ctx.Table("PackageAccessStat").Where("PackageID = ? AND UserSpaceID = ?", pkgID, spaceID).First(&ret).Error
	return ret, err
}

func (*PackageAccessStatDB) GetByPackageID(ctx SQLContext, pkgID types.PackageID) ([]types.PackageAccessStat, error) {
	var ret []types.PackageAccessStat
	err := ctx.Table("PackageAccessStat").Where("PackageID = ?", pkgID).Find(&ret).Error
	return ret, err
}

func (*PackageAccessStatDB) BatchGetByPackageID(ctx SQLContext, pkgIDs []types.PackageID) ([]types.PackageAccessStat, error) {
	if len(pkgIDs) == 0 {
		return nil, nil
	}

	var ret []types.PackageAccessStat
	err := ctx.Table("PackageAccessStat").Where("PackageID IN (?)", pkgIDs).Find(&ret).Error
	return ret, err
}

func (*PackageAccessStatDB) BatchAddCounter(ctx SQLContext, entries []AddAccessStatEntry) error {
	if len(entries) == 0 {
		return nil
	}

	accs := make([]types.PackageAccessStat, len(entries))
	for i, e := range entries {
		accs[i] = types.PackageAccessStat{
			PackageID:   e.PackageID,
			UserSpaceID: e.UserSpaceID,
			Counter:     e.Counter,
		}
	}

	return ctx.Clauses(clause.OnConflict{
		Columns: []clause.Column{{Name: "PackageID"}, {Name: "UserSpaceID"}},
		DoUpdates: clause.Assignments(map[string]any{
			"Counter": gorm.Expr("Counter + values(Counter)"),
		}),
	}).Table("PackageAccessStat").Create(&accs).Error
}

func (*PackageAccessStatDB) BatchUpdateAmount(ctx SQLContext, pkgIDs []types.PackageID, historyWeight float64) error {
	if len(pkgIDs) == 0 {
		return nil
	}

	sql := "UPDATE PackageAccessStat SET Amount = Amount * ? + Counter * (1 - ?), Counter = 0 WHERE PackageID IN (?)"
	return ctx.Exec(sql, historyWeight, historyWeight, pkgIDs).Error
}

func (*PackageAccessStatDB) UpdateAllAmount(ctx SQLContext, historyWeight float64) error {
	sql := "UPDATE PackageAccessStat SET Amount = Amount * ? + Counter * (1 - ?), Counter = 0"
	return ctx.Exec(sql, historyWeight, historyWeight).Error
}

func (*PackageAccessStatDB) DeleteByPackageID(ctx SQLContext, pkgID types.PackageID) error {
	return ctx.Table("PackageAccessStat").Where("PackageID = ?", pkgID).Delete(&types.PackageAccessStat{}).Error
}
