// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/usecase/filemetadata/anonymize_user_references.go
package filemetadata

import (
	"context"
	"fmt"

	"github.com/gocql/gocql"
	"go.uber.org/zap"

	dom_file "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/domain/file"
)

// AnonymizeUserReferencesUseCase handles anonymizing CreatedByUserID and ModifiedByUserID
// references when a user is deleted, replacing them with a special "deleted user" UUID.
type AnonymizeUserReferencesUseCase interface {
	Execute(ctx context.Context, userID gocql.UUID) (int, error)
}

type anonymizeUserReferencesUseCaseImpl struct {
	logger *zap.Logger
	repo   dom_file.FileMetadataRepository
}

// NewAnonymizeUserReferencesUseCase creates a new use case for anonymizing user references in files
func NewAnonymizeUserReferencesUseCase(
	logger *zap.Logger,
	repo dom_file.FileMetadataRepository,
) AnonymizeUserReferencesUseCase {
	return &anonymizeUserReferencesUseCaseImpl{
		logger: logger,
		repo:   repo,
	}
}

// DeletedUserUUID is a well-known UUID representing a deleted user
// UUID: 00000000-0000-0000-0000-000000000001 (DELETED_USER)
var DeletedUserUUID = gocql.UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}

func (uc *anonymizeUserReferencesUseCaseImpl) Execute(ctx context.Context, userID gocql.UUID) (int, error) {
	uc.logger.Info("Anonymizing user references in file metadata",
		zap.String("user_id", userID.String()))

	// Get all files created or modified by this user
	files, err := uc.repo.GetByCreatedByUserID(userID)
	if err != nil {
		uc.logger.Error("Failed to get files by created_by_user_id",
			zap.String("user_id", userID.String()),
			zap.Error(err))
		return 0, fmt.Errorf("failed to get files by creator: %w", err)
	}

	updatedCount := 0

	// Update each file to replace user references with deleted user UUID
	for _, file := range files {
		needsUpdate := false

		// Check if this file has references to the deleted user
		if file.CreatedByUserID == userID {
			file.CreatedByUserID = DeletedUserUUID
			needsUpdate = true
		}

		if file.ModifiedByUserID == userID {
			file.ModifiedByUserID = DeletedUserUUID
			needsUpdate = true
		}

		if needsUpdate {
			// Update the file with anonymized references
			if err := uc.repo.Update(file); err != nil {
				uc.logger.Error("Failed to anonymize user references in file",
					zap.String("file_id", file.ID.String()),
					zap.String("user_id", userID.String()),
					zap.Error(err))
				// Continue with other files even if one fails
				continue
			}
			updatedCount++
		}
	}

	uc.logger.Info("✅ Anonymized user references in file metadata",
		zap.String("user_id", userID.String()),
		zap.Int("files_updated", updatedCount))

	return updatedCount, nil
}
