<?php

namespace App\Classes\Modules\OpenAI\Services;

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

class UploadsOpenAIFiles
{
    public function execute(array $paths): array
    {
        try {
            $ids = [];
            foreach ($paths as $path) {
                $response = Http::withHeaders([
                    'Authorization' => 'Bearer ' . config('openai.api_key'),
                ])->attach(
                    'file',
                    fopen($path, 'r'),
                    basename($path)
                )->post(config('openai.base_url') . '/v1/files', [
                    'purpose' => 'user_data',
                ]);

                $data = $response->json();

                if ($response->successful() && isset($data['id'])) {
                    $ids[] = $data['id'];
                } else {
                    Log::error('File upload failed', [
                        'path' => $path,
                        'response' => $data
                    ]);
                }
            }

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