package model

import (
	"context"
	"fmt"
	"time"
	"xingfucha-server/common/globalkey"

	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ QueryModel = (*customQueryModel)(nil)

type (
	// QueryModel is an interface to be customized, add more methods here,
	// and implement the added methods in customQueryModel.
	QueryModel interface {
		queryModel
		DeleteBefore(ctx context.Context, before time.Time) (int64, error)
	}

	customQueryModel struct {
		*defaultQueryModel
	}
)

// NewQueryModel returns a model for the database table.
func NewQueryModel(conn sqlx.SqlConn, c cache.CacheConf) QueryModel {
	return &customQueryModel{
		defaultQueryModel: newQueryModel(conn, c),
	}
}

func (m *customQueryModel) DeleteBefore(ctx context.Context, before time.Time) (int64, error) {
	var affected int64 = 0

	// 使用事务处理批量删除
	err := m.defaultQueryModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
		query := fmt.Sprintf("DELETE FROM %s WHERE create_time < ? AND del_state = ?", m.defaultQueryModel.table)
		result, err := session.ExecCtx(ctx, query, before.Format("2006-01-02 15:04:05"), globalkey.DelStateNo)
		if err != nil {
			return err
		}

		rows, err := result.RowsAffected()
		if err != nil {
			return err
		}

		affected = rows
		return nil
	})

	if err != nil {
		return 0, err
	}

	return affected, nil
}
