package soap

import (
	"bytes"
	"daemonService/internal/models"
	"fmt"
	"io"
	"net/http"
	"time"
)

// func (s *ListaLeyendasFacturaService) enviarSOAPRequest(soapReq string) (*http.Response, []byte, error) {
func EnviarSOAPRequest(s *models.ServiceModel, soapReq string) (*http.Response, []byte, error) {
	var resp *http.Response
	var bodyBytes []byte
	var err error

	backoff := time.Second
	for i := 0; i < s.SOAPRetries; i++ {
		if i > 0 {
			time.Sleep(backoff)
			backoff *= 2
		}

		req, err := http.NewRequest("POST", s.SOAPEndpoint, bytes.NewBufferString(soapReq))
		if err != nil {
			continue
		}

		req.Header.Set("Content-Type", "text/xml; charset=utf-8")
		//req.Header.Set("apikey", s.APIKey)
		req.Header.Set(s.KeyToken, s.ValueToken)

		// Crea un transporte que ignore la configuración de proxy
		transport := &http.Transport{
			Proxy: nil, // Esto desactiva el uso de proxy
		}

		client := &http.Client{
			Transport: transport,
			Timeout:   30 * time.Second,
		}

		resp, err = client.Do(req)
		if err != nil || resp.StatusCode != http.StatusOK {
			continue
		}

		bodyBytes, err = io.ReadAll(resp.Body)
		if err != nil {
			resp.Body.Close()
			continue
		}

		return resp, bodyBytes, nil
	}

	return nil, nil, fmt.Errorf("fallo después de %d reintentos: %v", s.SOAPRetries, err)
}
