// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/service/blockedemail/delete.go
package blockedemail

import (
	"context"
	"strings"

	"go.uber.org/zap"

	"github.com/gocql/gocql"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config/constants"
	uc_blockedemail "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/usecase/blockedemail"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/httperror"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/validation"
)

type DeleteBlockedEmailService interface {
	Execute(ctx context.Context, email string) (*DeleteBlockedEmailResponseDTO, error)
}

type deleteBlockedEmailServiceImpl struct {
	config                    *config.Configuration
	logger                    *zap.Logger
	deleteBlockedEmailUseCase uc_blockedemail.DeleteBlockedEmailUseCase
}

func NewDeleteBlockedEmailService(
	config *config.Configuration,
	logger *zap.Logger,
	deleteBlockedEmailUseCase uc_blockedemail.DeleteBlockedEmailUseCase,
) DeleteBlockedEmailService {
	logger = logger.Named("DeleteBlockedEmailService")
	return &deleteBlockedEmailServiceImpl{
		config:                    config,
		logger:                    logger,
		deleteBlockedEmailUseCase: deleteBlockedEmailUseCase,
	}
}

func (svc *deleteBlockedEmailServiceImpl) Execute(ctx context.Context, email string) (*DeleteBlockedEmailResponseDTO, error) {
	//
	// STEP 1: Validation
	//
	if strings.TrimSpace(email) == "" {
		svc.logger.Warn("Failed validation with empty email")
		return nil, httperror.NewValidationError(map[string]string{"email": "Email is required"})
	}

	//
	// STEP 2: Get user ID from context
	//
	userID, ok := ctx.Value(constants.SessionUserID).(gocql.UUID)
	if !ok {
		svc.logger.Error("Failed getting user ID from context")
		return nil, httperror.NewInternalServerError("Authentication context error")
	}

	//
	// STEP 3: Delete blocked email
	//
	err := svc.deleteBlockedEmailUseCase.Execute(ctx, userID, email)
	if err != nil {
		svc.logger.Error("Failed to delete blocked email",
			zap.Any("error", err),
			zap.Any("user_id", userID),
			zap.String("email", validation.MaskEmail(email)))
		return nil, err
	}

	//
	// STEP 4: Return success response
	//
	response := &DeleteBlockedEmailResponseDTO{
		Success: true,
		Message: "Email unblocked successfully",
	}

	return response, nil
}
