package usecase

import (
	"context"
	"fmt"
	"strings"

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

// SetPrimaryProduct records an explicit member choice. Repository guards keep
// owner and ProductMatch identity checks close to the mutation as well.
func (s *Service) SetPrimaryProduct(ctx context.Context, ownerUID int64, opportunityID, productID, reason string) (*domain.Opportunity, error) {
	if ownerUID <= 0 || strings.TrimSpace(opportunityID) == "" || strings.TrimSpace(productID) == "" {
		return nil, fmt.Errorf("%w: owner, opportunity, and product required", domain.ErrValidation)
	}
	o, err := s.GetOpportunity(ctx, ownerUID, opportunityID)
	if err != nil {
		return nil, err
	}
	var match *domain.ProductMatch
	for _, candidate := range o.ProductMatches {
		if candidate != nil && candidate.ProductID == productID {
			match = candidate
			break
		}
	}
	if match == nil {
		return nil, fmt.Errorf("%w: product is not matched to this opportunity", domain.ErrValidation)
	}
	reason = strings.TrimSpace(reason)
	if reason == "" {
		return nil, fmt.Errorf("%w: primary product reason required", domain.ErrValidation)
	}
	return s.Repo.SetPrimaryProduct(ctx, ownerUID, opportunityID, productID, &domain.ProductPrimaryOverride{ActorUID: ownerUID, Reason: reason, At: domain.NowNano()})
}
