<?php

namespace App\Http\Controllers;

use App\Services\GeminiService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ChatbotController extends Controller
{
    public function __construct(
        private readonly GeminiService $geminiService,
    ) {}

    public function message(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'message'         => ['required', 'string', 'max:1000'],
            'history'         => ['sometimes', 'array', 'max:20'],
            'history.*.role'  => ['required_with:history', 'string', 'in:user,model'],
            'history.*.text'  => ['required_with:history', 'string', 'max:1000'],
        ]);

        $user = Auth::user();

        $reply = $this->geminiService->sendMessage(
            message:  $validated['message'],
            userType: $user->type,
            history:  $validated['history'] ?? [],
        );

        return $this->successResponse(payload: ['reply' => $reply]);
    }
}
