// 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.DataappsTable, DataappHandler)
}

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

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

	var dataappExtID string
	switch record.EventName {
	case types.OperationTypeInsert, types.OperationTypeModify:
		dataappExtID = newRecord.ExternalAppID
	case types.OperationTypeRemove:
		dataappExtID = oldRecord.ExternalAppID
	}
	return cacheManager.ClearDataappBaseInfo(ctx, dataappExtID)
}
