package services

import (
	"context"
	"daemonService/internal/models"
	"daemonService/internal/models/obtencionCodigos"
	"log"
	"sync"
)

func RunAllServices(ctx context.Context, services []models.SoapService, isCron bool) []error {
	var errors []error
	var wg sync.WaitGroup
	var mu sync.Mutex

	for _, service := range services {
		s := service
		wg.Add(1)
		go func() {
			defer wg.Done()
			serviceCtx, cancel := context.WithCancel(ctx)
			defer cancel()
			_, err := s.Execute(serviceCtx, nil, isCron)
			if err != nil {
				mu.Lock()
				errors = append(errors, err)
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	log.Println("Todos los servicios han sido ejecutados")
	return errors
}

func RunAllGetCodeServices(ctx context.Context, services []obtencionCodigos.CuisService, isCron bool) []error {
	var errors []error
	var wg sync.WaitGroup
	var mu sync.Mutex

	for _, service := range services {
		s := service
		wg.Add(1)
		go func() {
			defer wg.Done()
			serviceCtx, cancel := context.WithCancel(ctx)
			defer cancel()
			_, err := s.ExecuteGetCode(serviceCtx, nil, nil, isCron)
			if err != nil {
				mu.Lock()
				errors = append(errors, err)
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	log.Println("Todos los servicios han sido ejecutados Obtener Codigos")
	return errors
}
