<?php

namespace App\Services;

use Illuminate\Http\Client\Factory as HttpFactory;
use Illuminate\Http\UploadedFile;

class OpenAiTranscriptionService
{
    public function __construct(
        protected HttpFactory $http,
    ) {}

    public function isConfigured(): bool
    {
        return filled(config('services.openai.api_key'));
    }

    public function transcribe(UploadedFile $file): ?string
    {
        if (! $this->isConfigured()) {
            return null;
        }

        $contents = file_get_contents($file->getRealPath());

        if ($contents === false) {
            return null;
        }

        $response = $this->http
            ->baseUrl(rtrim((string) config('services.openai.base_url'), '/'))
            ->withToken((string) config('services.openai.api_key'))
            ->asMultipart()
            ->timeout(60)
            ->send('POST', '/audio/transcriptions', [
                'multipart' => [
                    [
                        'name' => 'model',
                        'contents' => (string) config('services.openai.transcription_model', 'gpt-4o-mini-transcribe'),
                    ],
                    [
                        'name' => 'file',
                        'contents' => $contents,
                        'filename' => $file->getClientOriginalName(),
                        'headers' => [
                            'Content-Type' => $file->getMimeType() ?: 'audio/webm',
                        ],
                    ],
                ],
            ]);

        if (! $response->successful()) {
            return null;
        }

        $text = $response->json('text');

        return is_string($text) ? trim($text) : null;
    }
}
