<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class AiController extends Controller
{
    public function chat(Request $request)
    {
        $validated = $request->validate([
            'message' => 'required|string|max:2000',
            'project_id' => 'nullable|integer',
            'conversation_history' => 'nullable|array',
        ]);

        $aiServiceUrl = config('services.ai.url', 'http://ai-service:8000');

        try {
            $response = Http::timeout(30)->post("{$aiServiceUrl}/api/chat", $validated);

            if ($response->successful()) {
                return response()->json($response->json());
            }

            return response()->json([
                'reply' => 'AI service fout: ' . $response->body(),
            ], 500);
        } catch (\Exception $e) {
            return response()->json([
                'reply' => 'AI service niet bereikbaar: ' . $e->getMessage(),
            ], 503);
        }
    }
}
