// Package handlers add by blacknc <blacknc@163.com> at 2024/05/20 15:56:26
package handlers

import (
	"context"
	"dataservices/internal/entity"
	"dataservices/internal/repository_ddb"
	service "dataservices/internal/service/common"
	ddbcacheworker "dataservices/worker/ddbcache"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodbstreams/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodbstreams/types"
)

func init() {
	ddbcacheworker.RegisterHandler(repository_ddb.AppClusterTable, AppClusterHandler)
}

func AppClusterHandler(ctx context.Context, event ddbcacheworker.Event, cacheManager service.CacheManager) error {

	record := event.Data
	var newRecord entity.AppCluster
	var oldRecord entity.AppCluster
	if err := attributevalue.UnmarshalMap(record.Dynamodb.NewImage, &newRecord); err != nil {
		return fmt.Errorf("failed to unmarshal dataapp cluster event new record:%v", err)
	}
	if err := attributevalue.UnmarshalMap(record.Dynamodb.OldImage, &oldRecord); err != nil {
		return fmt.Errorf("failed to unmarshal dataapp cluster event old record:%v", err)
	}

	var dataappID, clusterID uint64
	switch record.EventName {
	case types.OperationTypeInsert, types.OperationTypeModify:
		dataappID, clusterID = newRecord.DataappID, newRecord.ClusterID
	case types.OperationTypeRemove:
		dataappID, clusterID = oldRecord.DataappID, oldRecord.ClusterID
	}
	return cacheManager.ClearAppCluster(ctx, dataappID, clusterID)
}
