<?php

namespace App\Http\Controllers;

use App\Services\AI\AgentService;
use App\Repositories\AIConversationRepository;
use Illuminate\Http\Request;

class AIChatController extends Controller
{
    protected $agentService;
    protected $conversationRepo;

    public function __construct(AgentService $agentService, AIConversationRepository $conversationRepo)
    {
        $this->agentService = $agentService;
        $this->conversationRepo = $conversationRepo;
    }

    public function index()
    {
        return view('ai.chat');
    }

    public function send(Request $request)
    {
        $request->validate(['message' => 'required|string']);

        $result = $this->agentService->processMessage(auth()->user(), $request->message);

        if ($request->wantsJson()) {
            return response()->json($result);
        }

        return redirect()->route('ai.history')->with('success', 'Response received.');
    }

    public function history()
    {
        $conversations = $this->conversationRepo->getUserConversations(auth()->id());
        return view('ai.history', compact('conversations'));
    }

    public function show($id)
    {
        $conversation = $this->conversationRepo->find($id);
        $this->authorize('view', $conversation);
        return view('ai.show', compact('conversation'));
    }
}
