<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\OpenRouterService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OpenRouterController extends Controller
{
    public function __construct(private OpenRouterService $aiService) {}

    /**
     * POST /api/openrouter/analyze-ads
     * Ubaidi Ads Marketer — analyze ads data with AI
     */
    public function analyzeAds(Request $request): JsonResponse
    {
        $data = $request->json()->all();

        if (empty($data)) {
            return response()->json(['error' => 'Ads data প্রয়োজন'], 422);
        }

        try {
            $report = $this->aiService->analyzeAds($data);
            return response()->json(['success' => true, 'report' => $report]);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * POST /api/openrouter/chat
     * General Ubaidi AI chat
     */
    public function chat(Request $request): JsonResponse
    {
        $message = $request->input('message', '');
        $contextInput = $request->input('context', '');
        $history = $request->input('history', []);
        $extra = $request->input('extra', []);

        $context = is_array($contextInput) ? $contextInput : ['type' => $contextInput];
        $context['history'] = is_array($history) ? $history : [];
        $context['extra'] = is_array($extra) ? $extra : [];

        if (!$message) {
            return response()->json(['error' => 'message প্রয়োজন'], 422);
        }

        try {
            $reply = $this->aiService->chat($message, $context);
            return response()->json(['success' => true, 'reply' => $reply]);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * GET /api/openrouter/status
     * Check if AI server is reachable
     */
    public function status(): JsonResponse
    {
        $url = 'https://openrouter.ai/api/v1/chat/completions';

        try {
            // Just checking if we can resolve OpenRouter api
            $response = \Illuminate\Support\Facades\Http::timeout(5)->get('https://openrouter.ai/');
            return response()->json([
                'success' => true,
                'online'  => $response->successful(),
                'url'     => $url,
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'online' => false, 'error' => $e->getMessage()]);
        }
    }
}
