package api

import (
	"api-soap-facturacion/internal/logger"
	api1 "api-soap-facturacion/internal/soap/api"
	soapPkg "api-soap-facturacion/pkg/soap"
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// API1GetData maneja solicitudes GetData para API1
func (h *Handler) API1GetData(c *gin.Context) {
	// Obtener logger
	log := getLogger(c)

	// Obtener contexto con timeout
	ctx, cancel := context.WithTimeout(c.Request.Context(), h.config.App.RequestTimeout*time.Second)
	defer cancel()

	// Agregar ID de solicitud al contexto
	requestID := c.GetHeader("X-Request-ID")
	ctx = context.WithValue(ctx, soapPkg.RequestIDKey{}, requestID)

	// Parsear solicitud
	var requestData struct {
		ID   string `json:"id" binding:"required"`
		Type string `json:"type" binding:"required"`
		Date string `json:"date"`
	}

	if err := c.ShouldBindJSON(&requestData); err != nil {
		log.Error("Error al parsear solicitud", logger.NewField("error", err))
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Error al parsear solicitud",
		})
		return
	}

	// Crear solicitud SOAP
	request := api1.GetDataRequest{
		Namespace: "http://api1.example.com/soap",
		ID:        requestData.ID,
		Type:      requestData.Type,
		Date:      requestData.Date,
	}

	// Llamar a API1
	response, err := h.soapClients.API1.GetData(ctx, request)
	if err != nil {
		log.Error("Error al llamar a API1", logger.NewField("error", err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Error al realizar solicitud a API1",
		})
		return
	}

	// Retornar respuesta
	c.JSON(http.StatusOK, gin.H{
		"status":      response.Status,
		"resultCode":  response.ResultCode,
		"description": response.Description,
		"data":        response.Data,
	})
}
