package gateway

import (
	"go.uber.org/zap"

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

// RegisterInput represents the input for user registration validation
type RegisterInput struct {
	Email      string
	Password   string
	FirstName  string
	LastName   string
	TenantName string
	TenantSlug string
	Timezone   string

	// Consent fields
	AgreeTermsOfService                            bool
	AgreePromotions                                bool
	AgreeToTrackingAcrossThirdPartyAppsAndServices bool

	// Optional: IP address for audit trail
	CreatedFromIPAddress string
}

// ValidateRegistrationInputUseCase validates registration input
type ValidateRegistrationInputUseCase struct {
	logger *zap.Logger
}

// ProvideValidateRegistrationInputUseCase creates a new ValidateRegistrationInputUseCase
func ProvideValidateRegistrationInputUseCase(logger *zap.Logger) *ValidateRegistrationInputUseCase {
	return &ValidateRegistrationInputUseCase{
		logger: logger.Named("validate-registration-input-usecase"),
	}
}

// Execute validates the registration input fields
func (uc *ValidateRegistrationInputUseCase) Execute(input *RegisterInput) error {
	if input.Email == "" {
		uc.logger.Warn("email is required")
		return domainuser.ErrEmailRequired
	}

	if input.Password == "" {
		uc.logger.Warn("password is required")
		return domainuser.ErrPasswordRequired
	}

	if input.FirstName == "" {
		uc.logger.Warn("first name is required")
		return domainuser.ErrFirstNameRequired
	}

	if input.LastName == "" {
		uc.logger.Warn("last name is required")
		return domainuser.ErrLastNameRequired
	}

	if input.TenantName == "" {
		uc.logger.Warn("tenant name is required")
		return domaintenant.ErrNameRequired
	}

	if input.TenantSlug == "" {
		uc.logger.Warn("tenant slug is required")
		return domaintenant.ErrSlugRequired
	}

	// Validate Terms of Service agreement (REQUIRED)
	if !input.AgreeTermsOfService {
		uc.logger.Warn("terms of service agreement is required")
		return domainuser.ErrTermsOfServiceRequired
	}

	// Note: AgreePromotions and AgreeToTrackingAcrossThirdPartyAppsAndServices
	// are optional (defaults to false if not provided)

	// CWE-532: Use hashed/redacted fields to prevent PII in logs
	uc.logger.Debug("registration input validated successfully",
		logger.EmailHash(input.Email),
		logger.TenantSlugHash(input.TenantSlug),
		zap.Bool("agree_terms", input.AgreeTermsOfService),
		zap.Bool("agree_promotions", input.AgreePromotions),
		zap.Bool("agree_tracking", input.AgreeToTrackingAcrossThirdPartyAppsAndServices))

	return nil
}
