<?php

namespace App\Core\Ai\Services;

use App\Core\Ai\Models\AiHistoryModel;
use App\Core\License\Services\LicenseService;
use App\Core\Settings\Services\SettingService;

class AiService
{
    public function ask(string $prompt, array $context = []): array
    {
        $license = new LicenseService();
        if (! $license->canUseAi()) {
            return ['status' => 'denied', 'response' => 'Limite IA atteinte pour le plan actuel.'];
        }

        $settings = new SettingService();
        $model = (string) ($settings->get('openai.model') ?: env('openai.model') ?: 'gpt-4.1-mini');
        $builtPrompt = (new PromptBuilder())->build($prompt, $context);
        $result = (new OpenAiProvider())->send($builtPrompt, $model);

        (new AiHistoryModel())->insert([
            'user_id' => session('core_user_id'),
            'provider' => 'openai',
            'model' => $model,
            'prompt' => $prompt,
            'response' => $result['response'] ?? null,
            'tokens_input' => $result['tokens_input'] ?? null,
            'tokens_output' => $result['tokens_output'] ?? null,
            'status' => $result['status'] === 'success' || $result['status'] === 'stub' ? 'success' : $result['status'],
            'error_message' => $result['error_message'] ?? null,
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        $license->incrementUsage('ai_requests');

        return $result;
    }
}
