<?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\Models\KnowledgeBaseModel;
use App\Services\ActivityLogger;

final class KnowledgeBaseController extends BaseController
{
    public function index(Request $request): Response
    {
        $rows = (new KnowledgeBaseModel())->allActive();

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success($rows);
        }

        return $this->view('ai/knowledge-base', [
            'title' => 'Knowledge Base',
            'activeNav' => 'knowledge-base',
            'breadcrumbs' => [['Home', 'dashboard'], ['AI', 'ai-assistant'], ['Knowledge Base', 'knowledge-base']],
            'rows' => $rows,
            'businessLines' => Database::connection()->query('SELECT id, name FROM business_lines ORDER BY name')->fetchAll(),
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'category' => 'nullable|string|max:100',
            'question' => 'required|string|max:500',
            'answer' => 'required|string',
            'business_line_id' => 'nullable|integer|exists:business_lines,id',
        ]);
        $data['is_active'] = 1;

        $model = new KnowledgeBaseModel();
        $id = $model->insert($data, $this->currentUserId());
        ActivityLogger::record('knowledge_base_article', $id, 'kb_article_created', 'Knowledge base article created', category: 'admin');

        return AjaxResponse::created($model->find($id), 'Article created.');
    }

    public function update(Request $request, array $params): Response
    {
        $data = $this->validateOrFail($request, [
            'category' => 'nullable|string|max:100',
            'question' => 'required|string|max:500',
            'answer' => 'required|string',
            'business_line_id' => 'nullable|integer|exists:business_lines,id',
        ]);

        $id = (int) $params['id'];
        $model = new KnowledgeBaseModel();
        $model->update($id, $data, $this->currentUserId());
        ActivityLogger::record('knowledge_base_article', $id, 'kb_article_updated', 'Knowledge base article updated', category: 'admin');

        return AjaxResponse::success($model->find($id), 'Article updated.');
    }

    public function destroy(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new KnowledgeBaseModel())->delete($id, $this->currentUserId());
        ActivityLogger::record('knowledge_base_article', $id, 'kb_article_deleted', 'Knowledge base article deleted', category: 'admin');

        return AjaxResponse::success(null, 'Article deleted.');
    }
}
