<?php
declare(strict_types=1);

namespace App\Infrastructure\AI\OpenAI;

use App\Domain\AI\AiQuery;
use App\Domain\AI\AiQueryHandlerInterface;
use App\Domain\AI\AiResponse;
use App\Framework\Http\Headers;
use App\Framework\Http\Method;
use App\Framework\HttpClient\ClientRequest;
use App\Framework\HttpClient\HttpClient;

final readonly class OpenAiQueryHandler implements AiQueryHandlerInterface
{
    public function __construct(
        private HttpClient $httpClient,
        private string $openAiApiKey = ""
    ) {}

    public function __invoke(AiQuery $query): AiResponse
    {
        $url = 'https://api.openai.com/v1/chat/completions';

        $data = [
            'model' => $query->model->value,
            'messages' => $query->messages !== []
                ? $query->messages
                : [['role' => 'user', 'content' => $query->message]],
            'temperature' => $query->temperature,
        ];

        if ($query->maxTokens !== null) {
            $data['max_tokens'] = $query->maxTokens;
        }

        $request = ClientRequest::json(
            Method::POST,
            $url,
            $data
        )->with([
            'headers' => new Headers()
                ->with('Authorization', 'Bearer ' . $this->openAiApiKey)
        ]);

        $response = $this->httpClient->send($request);
        $body = json_decode($response->body, true);

        return new AiResponse(
            content: $body['choices'][0]['message']['content'] ?? '',
            provider: 'openai',
            model: $query->model->value,
            tokensUsed: $body['usage']['total_tokens'] ?? null
        );
    }
}
