<?php

declare(strict_types=1);

namespace App\Controllers;

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

final class ConversationController extends BaseController
{
    public function index(Request $request): Response
    {
        $model = new ConversationModel();
        $paginator = Paginator::fromRequest($request, defaultPerPage: 25);

        $filters = [
            'channel' => $request->query('channel'),
            'outcome' => $request->query('outcome'),
            'business_line_id' => $request->query('business_line_id'),
            'search' => $request->query('search'),
        ];

        $rows = $model->paginatedList($filters, $paginator);

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success(['rows' => $rows, 'meta' => $paginator->meta()]);
        }

        return $this->view('ai/conversation-logs', [
            'title' => 'Conversation Logs',
            'activeNav' => 'conversation-logs',
            'breadcrumbs' => [['Home', 'dashboard'], ['AI', 'ai-assistant'], ['Conversation Logs', 'conversation-logs']],
            'rows' => $rows,
            'meta' => $paginator->meta(),
            'businessLines' => Database::connection()->query('SELECT id, name FROM business_lines ORDER BY name')->fetchAll(),
        ]);
    }

    public function show(Request $request, array $params): Response
    {
        $model = new ConversationModel();
        $id = (int) $params['id'];
        $conversation = $model->findWithRelations($id);

        if ($conversation === null) {
            return AjaxResponse::notFound('Conversation not found.');
        }

        return AjaxResponse::success([
            'conversation' => $conversation,
            'messages' => $model->messages($id),
        ]);
    }

    public function stats(Request $request): Response
    {
        return AjaxResponse::success((new ConversationModel())->dashboardStats());
    }
}
