package page

import (
	"context"

	"go.uber.org/zap"

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

// UpdateSiteUsageUseCase updates site usage counters after indexing
type UpdateSiteUsageUseCase struct {
	siteRepo domainsite.Repository
	logger   *zap.Logger
}

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

// Execute updates the site's monthly page indexed count (for billing tracking)
func (uc *UpdateSiteUsageUseCase) Execute(
	ctx context.Context,
	site *domainsite.Site,
	indexedCount int,
) error {
	if indexedCount <= 0 {
		return nil
	}

	site.IncrementMonthlyPageCount(int64(indexedCount))

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

	return nil
}
