package page

import (
	"context"

	"go.uber.org/zap"

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

// IncrementSearchCountUseCase increments the search request counter for a site
type IncrementSearchCountUseCase struct {
	siteRepo domainsite.Repository
	logger   *zap.Logger
}

// ProvideIncrementSearchCountUseCase creates a new IncrementSearchCountUseCase
func ProvideIncrementSearchCountUseCase(
	siteRepo domainsite.Repository,
	logger *zap.Logger,
) *IncrementSearchCountUseCase {
	return &IncrementSearchCountUseCase{
		siteRepo: siteRepo,
		logger:   logger,
	}
}

// Execute increments the search count and updates the site usage tracking
func (uc *IncrementSearchCountUseCase) Execute(
	ctx context.Context,
	site *domainsite.Site,
) error {
	// Increment search request count
	site.IncrementSearchCount()

	uc.logger.Info("incremented search count",
		zap.String("site_id", site.ID.String()),
		zap.Int64("new_count", site.SearchRequestsCount))

	// Update usage tracking in database
	if err := uc.siteRepo.UpdateUsage(ctx, site); err != nil {
		uc.logger.Error("failed to update search usage", zap.Error(err))
		// Don't fail the search, just log the error and return
		return err
	}

	uc.logger.Info("search usage updated successfully",
		zap.String("site_id", site.ID.String()),
		zap.Int64("search_count", site.SearchRequestsCount))

	return nil
}
