package page

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

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

// CreatePageEntityUseCase creates a domain page entity from input
type CreatePageEntityUseCase struct {
	ipEncryptor *ipcrypt.IPEncryptor
	logger      *zap.Logger
}

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

// Execute converts SyncPageInput to a domain Page entity
func (uc *CreatePageEntityUseCase) Execute(
	siteID, tenantID gocql.UUID,
	input SyncPageInput,
) (*domainpage.Page, 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("page_id", input.PageID),
			zap.Error(err))
		return nil, err
	}

	return domainpage.NewPage(
		siteID,
		tenantID,
		input.PageID,
		input.Title,
		input.Content,
		input.Excerpt,
		input.URL,
		input.Status,
		input.PostType,
		input.Author,
		input.PublishedAt,
		input.ModifiedAt,
		encryptedIP,
	), nil
}
