package page

import (
	"context"
	"fmt"

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

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

// DeletePagesFromRepoUseCase deletes pages from the database repository
type DeletePagesFromRepoUseCase struct {
	pageRepo domainpage.Repository
	logger   *zap.Logger
}

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

// DeletePagesResult contains the result of page deletion
type DeletePagesResult struct {
	DeletedCount int
	FailedPages  []string
}

// Execute deletes specific pages from the database
func (uc *DeletePagesFromRepoUseCase) Execute(
	ctx context.Context,
	siteID gocql.UUID,
	pageIDs []string,
) (*DeletePagesResult, error) {
	result := &DeletePagesResult{
		DeletedCount: 0,
		FailedPages:  []string{},
	}

	if len(pageIDs) == 0 {
		return result, nil
	}

	// Use batch delete for multiple pages
	if len(pageIDs) > 1 {
		if err := uc.pageRepo.DeleteMultiple(ctx, siteID, pageIDs); err != nil {
			uc.logger.Error("failed to batch delete pages", zap.Error(err))
			return nil, fmt.Errorf("failed to delete pages: %w", err)
		}
		result.DeletedCount = len(pageIDs)
	} else {
		// Single page delete
		if err := uc.pageRepo.Delete(ctx, siteID, pageIDs[0]); err != nil {
			uc.logger.Error("failed to delete page",
				zap.String("page_id", pageIDs[0]),
				zap.Error(err))
			result.FailedPages = append(result.FailedPages, pageIDs[0])
		} else {
			result.DeletedCount = 1
		}
	}

	return result, nil
}

// ExecuteDeleteAll deletes all pages for a site from the database
func (uc *DeletePagesFromRepoUseCase) ExecuteDeleteAll(
	ctx context.Context,
	siteID gocql.UUID,
) (int64, error) {
	// Count pages before deletion
	count, err := uc.pageRepo.CountBySiteID(ctx, siteID)
	if err != nil {
		uc.logger.Error("failed to count pages", zap.Error(err))
		return 0, fmt.Errorf("failed to count pages: %w", err)
	}

	// Delete all pages from database
	if err := uc.pageRepo.DeleteBySiteID(ctx, siteID); err != nil {
		uc.logger.Error("failed to delete all pages", zap.Error(err))
		return 0, fmt.Errorf("failed to delete pages: %w", err)
	}

	return count, nil
}
