<?php

namespace App\Modules\Ai\Http\Controllers;

use App\Core\Http\Controllers\BaseApiController;
use App\Http\Requests\Api\AiChatRequest;
use App\Modules\Ai\Services\AiService;
use App\Services\Engagement\ConversationSyncService;
use App\Services\Engagement\PromptUsageService;
use App\Services\Engagement\UserLevelService;
use App\Services\Subscriptions\AiQuotaService;
use App\Services\Subscriptions\Exceptions\AiQuotaExceededException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * محادثة AI — يعيد النص في `data.response` لتطبيق Flutter.
 */
class AiController extends BaseApiController
{
    public function __construct(
        private readonly AiService $ai,
        private readonly ConversationSyncService $conversationSync,
        private readonly PromptUsageService $promptUsage,
        private readonly UserLevelService $levelService,
        private readonly AiQuotaService $quota,
    ) {}

    public function chat(AiChatRequest $request): JsonResponse
    {
        $user = $request->user();

        try {
            $this->quota->assertCanSendAiMessage($user);
        } catch (AiQuotaExceededException $e) {
            return $this->errorResponse($e->getMessage(), [
                'code' => $e->errorCode,
            ], 403);
        }

        try {
            $payload = $this->ai->chat($user, $request->validated('prompt'));
        } catch (Throwable $e) {
            return $this->errorResponse(
                'تعذر تنفيذ طلب الذكاء الاصطناعي.',
                ['detail' => $e->getMessage()],
                502
            );
        }

        $resolved = $payload['request']->resolve();
        $text = (string) ($resolved['response'] ?? '');

        $conversationId = null;
        if ($resolved['status'] ?? '' === 'completed' && $text !== '') {
            try {
                $conversationId = $this->conversationSync->sync(
                    $user,
                    $request->validated('conversation_id'),
                    $request->validated('prompt'),
                    $text
                );
                $this->promptUsage->record($request->validated('prompt'));
                $user->increment('ai_message_count');
                $user->refresh();
                $this->levelService->sync($user);
                $this->quota->recordSuccessfulAiMessage($user, (int) ($resolved['tokens_used'] ?? 0));
            } catch (Throwable $e) {
                Log::warning('ai.side_effects_failed', ['exception' => $e->getMessage()]);
            }
        }

        return $this->successResponse('تمت المعالجة', [
            'response' => $text,
            'conversation_id' => $conversationId,
        ]);
    }
}
