package user

import (
	"context"
	"fmt"

	"go.uber.org/zap"

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

// SaveUserToRepoUseCase saves a user to the repository
type SaveUserToRepoUseCase struct {
	repo   domainuser.Repository
	logger *zap.Logger
}

// ProvideSaveUserToRepoUseCase creates a new SaveUserToRepoUseCase
func ProvideSaveUserToRepoUseCase(
	repo domainuser.Repository,
	logger *zap.Logger,
) *SaveUserToRepoUseCase {
	return &SaveUserToRepoUseCase{
		repo:   repo,
		logger: logger.Named("save-user-to-repo-usecase"),
	}
}

// Execute saves a user to the repository
func (uc *SaveUserToRepoUseCase) Execute(ctx context.Context, tenantID string, user *domainuser.User) error {
	if err := uc.repo.Create(ctx, tenantID, user); err != nil {
		uc.logger.Error("failed to create user in repository",
			zap.String("user_id", user.ID),
			zap.String("email", user.Email),
			zap.String("tenant_id", tenantID),
			zap.Error(err))
		return fmt.Errorf("failed to create user: %w", err)
	}

	uc.logger.Info("user saved to repository",
		zap.String("user_id", user.ID),
		zap.String("email", user.Email),
		zap.String("tenant_id", tenantID))

	return nil
}
