package chat

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"

	"wechat-api/internal/logic/chat"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

// swagger:route post /v1/chat/completions chat ChatCompletions
//

//

//
// Parameters:
//  + name: body
//    require: true
//    in: body
//    type: CompApiReq
//
// Responses:
//  200: CompOpenApiResp

func ChatCompletionsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.CompApiReq
		/*
			if err := httpx.Parse(r, &req, true); err != nil {
				httpx.ErrorCtx(r.Context(), w, err)
				return
			}
		*/

		// 读取请求体
		body, err := io.ReadAll(r.Body)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		// 将请求体还原，以便后续处理
		r.Body = io.NopCloser(bytes.NewBuffer(body))
		logx.Info(string(body))
		err = json.Unmarshal([]byte(string(body)), &req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		// 打印请求体
		logx.Info(req)

		l := chat.NewChatCompletionsLogic(r.Context(), svcCtx)
		am, resp, err := l.ChatCompletions(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			if !am {
				httpx.OkJsonCtx(r.Context(), w, resp)
			} else {
				httpx.OkJsonCtx(r.Context(), w, types.BaseDataInfo{Code: 0, Msg: "请求已经受理"})
			}
		}
	}
}
