<?php

namespace ZenoChatbot\Http\Controller\Api\V1;

use ZenoChatbot\Helper\Resources;
use ZenoChatbot\Helper\Security;
use ZenoChatbot\Services\Indexing\ContentIndexService;
use ZenoChatbot\Services\Indexing\Strategies\KnowledgeNoteIndex;

class KnowledgeNotesIndexController
{
    private function indexingService(): ContentIndexService
    {
        return ContentIndexService::create(Resources::getBaseDirPath());
    }

    public function getKnowledgeNotes(\WP_REST_Request $request)
    {
        if (!Security::currentUserCan('manage_options')) {
            return [
                'success' => false,
                'message' => 'Insufficient permissions',
                'status' => 403
            ];
        }

        try {
            return $this->mapKnowledgeGetResponse($this->indexingService()->get(new KnowledgeNoteIndex()));
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to get knowledge notes',
                'error' => $e->getMessage(),
                'status' => 500,
            ];
        }
    }

    public function saveKnowledgeNotes(\WP_REST_Request $request)
    {
        if (!Security::currentUserCan('manage_options')) {
            return [
                'success' => false,
                'message' => 'Insufficient permissions',
                'status' => 403
            ];
        }

        $content = sanitize_textarea_field($request->get_param('content'));

        if (strlen($content) > 200000) {
            return [
                'success' => false,
                'message' => 'Knowledge notes content is too large.',
                'status' => 400,
            ];
        }

        try {
            $result = $this->indexingService()->index(new KnowledgeNoteIndex($content));
            return $this->mapKnowledgeSaveResponse($result);
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to save knowledge notes',
                'error' => $e->getMessage(),
                'status' => 500,
            ];
        }
    }

    public function clearKnowledgeNotes(\WP_REST_Request $request)
    {
        if (!Security::currentUserCan('manage_options')) {
            return [
                'success' => false,
                'message' => 'Insufficient permissions',
                'status' => 403
            ];
        }

        try {
            $result = $this->indexingService()->clear(new KnowledgeNoteIndex());
            return $this->mapKnowledgeClearResponse($result);
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to clear knowledge notes',
                'error' => $e->getMessage(),
                'status' => 500,
            ];
        }
    }

    public function getKnowledgeNotesStatus(\WP_REST_Request $request)
    {
        if (!Security::currentUserCan('manage_options')) {
            return [
                'success' => false,
                'message' => 'Insufficient permissions',
                'status' => 403
            ];
        }

        try {
            return [
                'success' => true,
                'data' => $this->indexingService()->stats(new KnowledgeNoteIndex()),
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to get knowledge notes status',
                'error' => $e->getMessage(),
                'status' => 500,
            ];
        }
    }

    /** @param array<string,mixed> $serviceResult */
    private function mapKnowledgeGetResponse(array $serviceResult): array
    {
        return [
            'success' => true,
            'data' => [
                'content' => (string) ($serviceResult['data']['content'] ?? ''),
            ],
        ];
    }

    /** @param array<string,mixed> $serviceResult */
    private function mapKnowledgeSaveResponse(array $serviceResult): array
    {
        if (!($serviceResult['success'] ?? false)) {
            return [
                'success' => false,
                'message' => (string) ($serviceResult['message'] ?? 'Failed to save knowledge notes'),
                'status' => 500,
            ];
        }

        return [
            'success' => true,
            'message' => (string) ($serviceResult['message'] ?? 'Knowledge notes saved successfully.'),
            'data' => $serviceResult['data'] ?? [],
        ];
    }

    /** @param array<string,mixed> $serviceResult */
    private function mapKnowledgeClearResponse(array $serviceResult): array
    {
        if (!($serviceResult['success'] ?? false)) {
            return [
                'success' => false,
                'message' => (string) ($serviceResult['message'] ?? 'Failed to clear knowledge notes'),
                'status' => 500,
            ];
        }

        return [
            'success' => true,
            'message' => (string) ($serviceResult['message'] ?? 'Knowledge notes index cleared successfully.'),
            'data' => $serviceResult['data'] ?? [],
        ];
    }
}
