package access

import (
	"context"
	"fmt"
	"strings"

	"sub2api-cn-relay-manager/internal/host/sub2api"
)

func (s *Service) prepareSubscriptionPlan(ctx context.Context, req ClosureRequest, plan closurePlan) (closurePlan, error) {
	for _, target := range req.Subscriptions {
		resolvedTarget := target.UserID
		accessRef, err := s.host.EnsureSubscriptionAccess(ctx, sub2api.EnsureSubscriptionAccessRequest{
			UserSelector: target.UserID,
			GroupID:      req.GroupID,
		})
		if err != nil {
			return closurePlan{}, fmt.Errorf("ensure subscription access for %s: %w", target.UserID, err)
		}
		if strings.TrimSpace(accessRef.UserID) != "" {
			resolvedTarget = accessRef.UserID
		}
		if strings.TrimSpace(accessRef.APIKey) != "" {
			plan.effectiveProbeAPIKey = strings.TrimSpace(accessRef.APIKey)
			plan.effectiveProbeKeySource = ProbeKeySourceManagedSubscription
		}
		if _, err := s.host.AssignSubscription(ctx, sub2api.AssignSubscriptionRequest{
			UserID:       resolvedTarget,
			GroupID:      req.GroupID,
			DurationDays: target.DurationDays,
		}); err != nil {
			return closurePlan{}, fmt.Errorf("assign subscription for %s: %w", target.UserID, err)
		}
	}
	return plan, nil
}
