package tasks

import (
	"context"
	"strconv"
	"time"

	"github.com/spf13/viper"

	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"

	"github.com/tidbcloud/auditlog/internal/dao"
	"github.com/tidbcloud/auditlog/internal/entity"
)

const (
	ClearAuditLogWhitelistKey = "server.clearAuditLogWhitelist"
)

func DeleteOldEvents() {
	ctx := context.TODO()
	createdAt := time.Now().AddDate(0, 0, -90)

	db := entity.GetDB()
	d := dao.NewAuditDao()

	tilog.Info(ctx, "start to delete old events", zap.Time("created_at", createdAt), zap.Time("now", time.Now()))

	whitelistOrgIds := viper.GetStringSlice(ClearAuditLogWhitelistKey)
	tilog.Info(ctx, "delete old events, get org whitelist", zap.Any("whitelist", whitelistOrgIds))
	if len(whitelistOrgIds) == 0 {
		tilog.Error(ctx, "delete old events, get org whitelist from one config is empty", zap.Any("key", ClearAuditLogWhitelistKey))
		return
	}

	var err error
	if len(whitelistOrgIds) > 0 {
		var orgIds []uint64
		for _, wl := range whitelistOrgIds {
			intOrgId, _ := strconv.ParseUint(wl, 10, 64)
			orgIds = append(orgIds, intOrgId)
		}
		tilog.Info(ctx, "delete old events conditions", zap.Any("whitelist", orgIds), zap.Time("created_at", createdAt))
		err = d.DeleteEventsOlderThanAndNotInOrgIds(ctx, db, orgIds, createdAt)

	} else {
		err = d.DeleteEventsOlderThan(ctx, db, createdAt)
	}
	tilog.Info(ctx, "after delete old events", zap.Time("created_at", createdAt), zap.Time("now", time.Now()), zap.Error(err))
}
