<?php

namespace App\Classes\Modules\OpenAI\Services;

use Illuminate\Support\Facades\Http;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Exceptions\ConnectionErrorException;

class CreatesChatGPTResponseWithFiles
{
    public function execute(string $userPrompt, array $fileIds)
    {
        try {
            $fileContents = [];
            foreach ($fileIds as $fileId) {
                $fileContents[] = [
                    'type' => 'input_file',
                    'file_id' => $fileId,
                ];
            }

            $inputs = array_merge([
                [
                    'type' => 'input_text',
                    'text' => $userPrompt,
                ]
            ], $fileContents);

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . config('openai.api_key'),
                'Content-Type' => 'application/json',
            ])->post(config('openai.base_url') . '/v1/responses', [
                'model' => 'gpt-4.1-mini',
                'input' => [
                    [
                        'role' => 'user',
                        'content' => $inputs,
                    ],
                ],
            ]);

            return $response->json();
        }
        catch (\Illuminate\Http\Client\ConnectionException $exception) {
            $error = 'Failed to connect to ChatGPT API';
            throw new ConnectionErrorException($error, $exception->getMessage(), $userPrompt, $exception->getTraceAsString());
        }
        catch (\Exception $exception) {
            throw new MalformedRequestException('Unable to get correct response from ChatGPT API: ' . $exception->getMessage());
        }
    }
}
