<?php

namespace App\Modules\Ai\Services;

use App\Core\Contracts\Ai\AiCompletionPort;
use App\Http\Resources\AiRequestResource;
use App\Models\Setting;
use App\Modules\Ai\Repositories\Contracts\AiRequestRepositoryInterface;
use App\Modules\Users\Models\User;
use Throwable;

/**
 * Orchestrates AI request persistence + provider call (mock or real).
 */
final class AiService
{
    public function __construct(
        private readonly AiRequestRepositoryInterface $aiRequests,
        private readonly AiCompletionPort $aiCompletion,
    ) {}

    /**
     * @return array{request: AiRequestResource}
     */
    public function chat(User $user, string $prompt): array
    {
        $settings = Setting::current();

        if (! $settings->ai_enabled) {
            $record = $this->aiRequests->create([
                'user_id' => $user->id,
                'prompt' => $prompt,
                'response' => 'خدمة الذكاء الاصطناعي معطلة من إعدادات المنصة.',
                'tokens_used' => 0,
                'status' => 'failed',
            ]);

            return [
                'request' => new AiRequestResource($record),
            ];
        }

        $record = $this->aiRequests->create([
            'user_id' => $user->id,
            'prompt' => $prompt,
            'response' => null,
            'tokens_used' => 0,
            'status' => 'pending',
        ]);

        try {
            $result = $this->aiCompletion->complete($prompt, $user->id);

            $record = $this->aiRequests->update($record, [
                'response' => $result['response'],
                'tokens_used' => $result['tokens_used'],
                'status' => 'completed',
            ]);
        } catch (Throwable $e) {
            $record = $this->aiRequests->update($record, [
                'response' => $e->getMessage(),
                'tokens_used' => 0,
                'status' => 'failed',
            ]);

            throw $e;
        }

        return [
            'request' => new AiRequestResource($record),
        ];
    }
}
