package site

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

	domainsite "codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/domain/site"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/security/ipcrypt"
)

// CreateSiteEntityUseCase creates a site domain entity
type CreateSiteEntityUseCase struct {
	ipEncryptor *ipcrypt.IPEncryptor
	logger      *zap.Logger
}

// ProvideCreateSiteEntityUseCase creates a new CreateSiteEntityUseCase
func ProvideCreateSiteEntityUseCase(
	ipEncryptor *ipcrypt.IPEncryptor,
	logger *zap.Logger,
) *CreateSiteEntityUseCase {
	return &CreateSiteEntityUseCase{
		ipEncryptor: ipEncryptor,
		logger:      logger,
	}
}

// CreateSiteEntityInput contains the data needed to create a site entity
type CreateSiteEntityInput struct {
	TenantID          gocql.UUID
	Domain            string
	SiteURL           string
	APIKeyHash        string
	APIKeyPrefix      string
	APIKeyLastFour    string
	VerificationToken string
	IPAddress         string // Plain IP address (will be encrypted before storage)
}

// Execute creates a new site domain entity
func (uc *CreateSiteEntityUseCase) Execute(input *CreateSiteEntityInput) (*domainsite.Site, error) {
	// Encrypt IP address (CWE-359: GDPR compliance)
	encryptedIP, err := uc.ipEncryptor.Encrypt(input.IPAddress)
	if err != nil {
		uc.logger.Error("failed to encrypt IP address",
			zap.String("domain", input.Domain),
			zap.Error(err))
		return nil, err
	}

	site := domainsite.NewSite(
		input.TenantID,
		input.Domain,
		input.SiteURL,
		input.APIKeyHash,
		input.APIKeyPrefix,
		input.APIKeyLastFour,
		encryptedIP,
	)
	site.VerificationToken = input.VerificationToken

	uc.logger.Info("site entity created",
		zap.String("site_id", site.ID.String()),
		zap.String("domain", site.Domain))

	return site, nil
}
