package activity

import (
	"bindbox-game/internal/repository/mysql/dao"
	"context"
)

// DeleteIssue 删除活动期
// 参数: issueID 期ID
// 返回: 错误信息
func (s *service) DeleteIssue(ctx context.Context, issueID int64) error {
	return s.writeDB.Transaction(func(tx *dao.Query) error {
		logs, err := tx.ActivityDrawLogs.WithContext(ctx).Where(tx.ActivityDrawLogs.IssueID.Eq(issueID)).Find()
		if err != nil {
			return err
		}
		var drawLogIDs []int64
		for _, lg := range logs {
			drawLogIDs = append(drawLogIDs, lg.ID)
		}

		if _, err = tx.ActivityRewardSettings.WithContext(ctx).Where(tx.ActivityRewardSettings.IssueID.Eq(issueID)).Delete(); err != nil {
			return err
		}
		if _, err = tx.ActivityDrawEffects.WithContext(ctx).Where(tx.ActivityDrawEffects.IssueID.Eq(issueID)).Delete(); err != nil {
			return err
		}
		if len(drawLogIDs) > 0 {
			if _, err = tx.ActivityDrawEffects.WithContext(ctx).Where(tx.ActivityDrawEffects.DrawLogID.In(drawLogIDs...)).Delete(); err != nil {
				return err
			}
			if _, err = tx.ActivityDrawReceipts.WithContext(ctx).Where(tx.ActivityDrawReceipts.DrawLogID.In(drawLogIDs...)).Delete(); err != nil {
				return err
			}
			if _, err = tx.UserItemCards.WithContext(ctx).Where(tx.UserItemCards.UsedDrawLogID.In(drawLogIDs...)).Delete(); err != nil {
				return err
			}
		}
		if _, err = tx.UserItemCards.WithContext(ctx).Where(tx.UserItemCards.UsedIssueID.Eq(issueID)).Delete(); err != nil {
			return err
		}

		if _, err = tx.SystemItemCards.WithContext(ctx).Where(tx.SystemItemCards.IssueID.Eq(issueID)).Delete(); err != nil {
			return err
		}
		if _, err = tx.ActivityDrawLogs.WithContext(ctx).Where(tx.ActivityDrawLogs.IssueID.Eq(issueID)).Delete(); err != nil {
			return err
		}
		if _, err = tx.ActivityIssues.WithContext(ctx).Where(tx.ActivityIssues.ID.Eq(issueID)).Delete(); err != nil {
			return err
		}
		return nil
	})
}
