package channel

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"one-api/common/client"
	"one-api/common/ctxkey"
	"one-api/relay/util"

	"github.com/gin-gonic/gin"
)

func SetupCommonRequestHeader(c *gin.Context, req *http.Request, meta *util.RelayMeta) {
	req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
	req.Header.Set("Accept", c.Request.Header.Get("Accept"))
	headers := meta.Headers
	for headerKey, headerValue := range headers {
		req.Header.Set(headerKey, headerValue)
	}
	if meta.IsStream && c.Request.Header.Get("Accept") == "" {
		req.Header.Set("Accept", "text/event-stream")
	}
}

func DoRequestHelper(a Adaptor, c *gin.Context, meta *util.RelayMeta, requestBody io.Reader) (*http.Response, error) {
	fullRequestURL, err := a.GetRequestURL(meta)
	if err != nil {
		return nil, fmt.Errorf("get request url failed: %w", err)
	}

	req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
	if err != nil {
		return nil, fmt.Errorf("new request failed: %w", err)
	}
	req.Header.Set("Content-Type", c.GetString(ctxkey.ContentType))
	err = a.SetupRequestHeader(c, req, meta)
	if err != nil {
		return nil, fmt.Errorf("setup request header failed: %w", err)
	}
	client, err := client.GetProxiedHttpClient(meta.ProxyURL)
	if err != nil {
		return nil, fmt.Errorf("get proxied http client failed: %w", err)
	}
	resp, err := DoRequest(c, req, client)
	if err != nil {
		return nil, fmt.Errorf("do request failed: %w", err)
	}
	return resp, nil
}

func DoRequest(c *gin.Context, req *http.Request, client *http.Client) (*http.Response, error) {
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, errors.New("resp is nil")
	}
	_ = req.Body.Close()
	_ = c.Request.Body.Close()
	return resp, nil
}
