package usecase

import (
	"context"
	"fmt"
	"strings"

	"apps/backend/internal/module/radar/domain"
)

// PauseProductUnavailable is idempotent and keeps the historical watch. It is
// used by sweep validation and by Scout's product-delete lifecycle bridge.
func (s *Service) PauseProductUnavailable(ctx context.Context, ownerUID int64, watchID, reason string) (*domain.RadarWatch, error) {
	w, err := s.GetWatch(ctx, ownerUID, watchID)
	if err != nil {
		return nil, err
	}
	if reason == "" {
		reason = domain.PauseReasonProductUnavailable
	}
	if reason != domain.PauseReasonProductUnavailable && reason != domain.PauseReasonBrandUnavailable {
		return nil, fmt.Errorf("%w: invalid unavailable pause reason", domain.ErrValidation)
	}
	if w.Status == domain.WatchArchived {
		return w, nil
	}
	w.Status = domain.WatchPaused
	w.PauseReason = strings.TrimSpace(reason)
	w.UpdatedAt = domain.NowNano()
	if err := s.Repo.SaveWatch(ctx, w); err != nil {
		return nil, err
	}
	return w, nil
}

// PauseProductWatches pauses all active watches bound to a product before the
// catalog owner deletes it. The operation is idempotent for already-paused or
// archived history.
func (s *Service) PauseProductWatches(ctx context.Context, ownerUID int64, productID string) (int, error) {
	if ownerUID <= 0 || strings.TrimSpace(productID) == "" {
		return 0, fmt.Errorf("%w: owner and product required", domain.ErrValidation)
	}
	watches, _, err := s.Repo.ListWatches(ctx, ownerUID, domain.WatchListFilter{ProductID: strings.TrimSpace(productID), Page: 1, PageSize: 100})
	if err != nil {
		return 0, err
	}
	count := 0
	for _, watch := range watches {
		if watch.Status != domain.WatchActive {
			continue
		}
		if _, err := s.PauseProductUnavailable(ctx, ownerUID, watch.ID, domain.PauseReasonProductUnavailable); err != nil {
			return count, err
		}
		count++
	}
	return count, nil
}
