<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\OpenAIService;
use App\Models\Demande;

class OpenAIController extends Controller
{
    private $openAIService;

    public function __construct(OpenAIService $openAIService)
    {
        $this->openAIService = $openAIService;
    }

    public function getChatCompletion($demande_id)
    {

        $demande = Demande::find($demande_id);
        if (!$demande) {
            return response()->json(['error' => 'Demande not found'], 404);
        }

        if($demande->pub_text) {
            return response()->json(['response' => $demande->pub_text], 200);
        }

        $message = $this->openAIService->buildMessage($demande);
        
        $response = $this->openAIService->getChatCompletion($message);
        if ($response != null) {
            $demande->pub_text = $response;
            $demande->save();
        
            return response()->json(['response' => $response], 200);
        }

        return response()->json(['error' => 'Failed to get response from OpenAI'], 500);
    }
}