<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Helpers\Paginator;
use App\Models\ConversationModel;
use App\Services\AiAssistantService;

final class AiAssistantController extends BaseController
{
    public function index(Request $request): Response
    {
        return $this->view('ai/assistant', [
            'title' => 'AI Assistant',
            'activeNav' => 'ai-assistant',
            'breadcrumbs' => [['Home', 'dashboard'], ['AI', 'ai-assistant'], ['AI Assistant', 'ai-assistant']],
        ]);
    }

    public function ask(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'message' => 'required|string|max:2000',
            'business_line_id' => 'required|integer|exists:business_lines,id',
        ]);

        $history = $request->input('history', []);
        if (!is_array($history)) {
            $history = [];
        }

        $service = new AiAssistantService();
        $result = $service->ask($data['message'], $history, $this->currentUserId(), (int) $data['business_line_id']);

        if (!$result['success']) {
            return AjaxResponse::error($result['error'], 422);
        }

        $conversationId = $service->logExchange(
            $request->input('conversation_id') ? (int) $request->input('conversation_id') : null,
            (int) $data['business_line_id'],
            $this->currentUserId(),
            $data['message'],
            $result['reply']
        );

        return AjaxResponse::success([
            'reply' => $result['reply'],
            'conversation_id' => $conversationId,
            'tool_calls_made' => $result['tool_calls_made'],
        ]);
    }

    public function history(Request $request): Response
    {
        $paginator = Paginator::fromRequest($request, defaultPerPage: 20);
        $rows = (new ConversationModel())->paginatedList(['channel' => 'ai_assistant'], $paginator);

        return AjaxResponse::success(['rows' => $rows, 'meta' => $paginator->meta()]);
    }
}
