package page

import (
	"context"
	"fmt"

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

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

// GetPageStatisticsUseCase retrieves page count statistics
type GetPageStatisticsUseCase struct {
	pageRepo domainpage.Repository
	logger   *zap.Logger
}

// ProvideGetPageStatisticsUseCase creates a new GetPageStatisticsUseCase
func ProvideGetPageStatisticsUseCase(
	pageRepo domainpage.Repository,
	logger *zap.Logger,
) *GetPageStatisticsUseCase {
	return &GetPageStatisticsUseCase{
		pageRepo: pageRepo,
		logger:   logger,
	}
}

// PageStatistics contains page count statistics
type PageStatistics struct {
	TotalPages     int64
	PublishedPages int64
	DraftPages     int64
}

// Execute retrieves page statistics for a site
func (uc *GetPageStatisticsUseCase) Execute(
	ctx context.Context,
	siteID gocql.UUID,
) (*PageStatistics, error) {
	// Count total pages in database
	totalPages, err := uc.pageRepo.CountBySiteID(ctx, siteID)
	if err != nil {
		uc.logger.Error("failed to count pages", zap.Error(err))
		return nil, fmt.Errorf("failed to count pages: %w", err)
	}

	// Get all pages to count by status (this could be optimized with a dedicated query)
	pages, err := uc.pageRepo.GetBySiteID(ctx, siteID)
	if err != nil {
		uc.logger.Error("failed to get pages", zap.Error(err))
		return nil, fmt.Errorf("failed to get pages: %w", err)
	}

	// Count pages by status
	var publishedPages, draftPages int64
	for _, page := range pages {
		if page.Status == "publish" {
			publishedPages++
		} else if page.Status == "draft" {
			draftPages++
		}
	}

	uc.logger.Info("page statistics retrieved",
		zap.String("site_id", siteID.String()),
		zap.Int64("total", totalPages),
		zap.Int64("published", publishedPages),
		zap.Int64("draft", draftPages))

	return &PageStatistics{
		TotalPages:     totalPages,
		PublishedPages: publishedPages,
		DraftPages:     draftPages,
	}, nil
}
