package com.aiup.chatgptserver.controller;

import com.aiup.chatgptserver.service.GptChatQuery;
import com.aiup.chatgptserver.service.GptChatResponse;
import com.aiup.chatgptserver.service.OpenAiService;
import com.aiup.chatgptserver.service.R;
import com.aiup.chatgptserver.service.openai.ChatResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1/gpt")
@RequiredArgsConstructor
public class ChatController {
    @Autowired
    private OpenAiService openAiService;

    @PostMapping("/chat")
    public R<GptChatResponse> chat(@RequestBody @Validated GptChatQuery query) {
        try {
            if(StringUtils.isEmpty(query.getPwd()) || !query.getPwd().equals("yunzhongyu123abcd"))
            {
                return R.error();
            }
            ChatResponse chat = openAiService.chat(query);
            GptChatResponse response = new GptChatResponse();
            response.setContent(chat.getChoices().get(0).getMessage().getContent());
            return R.ok(response);
        }
        catch (Exception ep){
            ep.printStackTrace();
            return R.error(ep.toString());
        }
    }
}
