package user

import (
	"context"
	"fmt"

	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/domain/user"
)

// DeleteUserUseCase handles user deletion operations
// Used as compensating transaction in SAGA pattern
type DeleteUserUseCase struct {
	repo   user.Repository
	logger *zap.Logger
}

// ProvideDeleteUserUseCase creates a new DeleteUserUseCase for dependency injection
func ProvideDeleteUserUseCase(
	repo user.Repository,
	logger *zap.Logger,
) *DeleteUserUseCase {
	return &DeleteUserUseCase{
		repo:   repo,
		logger: logger.Named("delete-user-usecase"),
	}
}

// Execute deletes a user by ID within a tenant
// This is used as a compensating transaction
//
// IMPORTANT: This operation must be idempotent!
func (uc *DeleteUserUseCase) Execute(ctx context.Context, tenantID, userID string) error {
	uc.logger.Info("deleting user",
		zap.String("tenant_id", tenantID),
		zap.String("user_id", userID))

	// Validate inputs
	if tenantID == "" {
		return fmt.Errorf("tenant ID cannot be empty")
	}
	if userID == "" {
		return fmt.Errorf("user ID cannot be empty")
	}

	// Execute deletion using repository
	if err := uc.repo.Delete(ctx, tenantID, userID); err != nil {
		uc.logger.Error("failed to delete user",
			zap.String("tenant_id", tenantID),
			zap.String("user_id", userID),
			zap.Error(err))
		return fmt.Errorf("failed to delete user: %w", err)
	}

	uc.logger.Info("user deleted successfully",
		zap.String("tenant_id", tenantID),
		zap.String("user_id", userID))

	return nil
}
