package history

import (
	"context"

	"gorm.io/gorm/clause"

	"github.com/tidbcloud/tiinf/errs"

	"github.com/tidbcloud/account/internel/dao/entity"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

func (d *HistoryDao) CreateOrUpdateEventHistoryLast(ctx context.Context, tx *gorm.DB, eventHistory *entity.EventHistoryLast) error {
	tx.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "identity_id"}, {Name: "identity_type"}, {Name: "event"}},
		DoUpdates: clause.AssignmentColumns([]string{"target_type", "target_id", "updated_at"}),
	}).Create(eventHistory)
	tilog.Info(ctx, "HistoryDao CreateOrUpdateEventHistoryLast success: ", zap.Any("history: ", eventHistory))

	return nil
}

func (d *HistoryDao) GetLastHistoryLast(ctx context.Context, tx *gorm.DB, filter SingleEventHistoryFilter) (*entity.EventHistoryLast, error) {
	var historyLast entity.EventHistoryLast

	//qs := entity.NewEventHistoryQuerySet(tx)
	if filter.IdentityID == 0 || filter.IdentityType == "" || filter.Event == "" {
		return nil, errs.NewBadRequest("param must not empty", nil)

	}
	tx = tx.Where("identity_id = ? and identity_type = ? and event = ?", filter.IdentityID, filter.IdentityType, filter.Event)

	err := tx.Take(&historyLast).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}

	tilog.Info(ctx, "GetLastEventHistory ", zap.Any("result", historyLast), zap.Any("filter", filter))
	return &historyLast, nil
}
func (d *HistoryDao) ListEventHistoryLast(ctx context.Context, tx *gorm.DB, filter EventHistoryFilter) ([]entity.EventHistoryLast, error) {

	if len(filter.IdentityIDs) == 0 || len(filter.IdentityTypes) == 0 || len(filter.Events) == 0 {
		return nil, errs.NewBadRequest("param must not empty", nil)

	}
	var historyLasts []entity.EventHistoryLast
	tx = tx.Model(&entity.EventHistoryLast{})

	if len(filter.IdentityIDs) > 0 {
		tx = tx.Where("identity_id in (?)", filter.IdentityIDs)
	}
	if len(filter.IdentityTypes) > 0 {
		tx = tx.Where("identity_type in (?)", filter.IdentityTypes)
	}

	if len(filter.Events) > 0 {
		tx = tx.Where("event in (?)", filter.Events)
	}
	if len(filter.TargetIDs) > 0 {
		tx = tx.Where("target_id in (?)", filter.TargetIDs)
	}
	if len(filter.TargetTypes) > 0 {
		tx = tx.Where("target_type in (?)", filter.TargetTypes)
	}

	if err := tx.Find(&historyLasts).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return historyLasts, nil
		}
		tilog.Error(ctx, "ListEventHistoryLast error", zap.Error(err))
		return nil, err
	}

	//tilog.Info(ctx, "ListEventHistoryLast ", zap.Any("result", historyLasts), zap.Any("filter", filter))
	return historyLasts, nil
}
