<?php

namespace ZenoChatbot\Services\Indexing\Strategies;

use ZenoChatbot\Helper\ExternalSources;
use ZenoChatbot\Services\Indexing\Contracts\IndexStrategyInterface;

class ExternalContentIndex implements IndexStrategyInterface
{
    /** @var array<int,array<string,mixed>> */
    private $items;

    /** @param array<int,array<string,mixed>> $items */
    public function __construct(array $items = [])
    {
        $this->items = $items;
    }

    public function key(): string
    {
        return 'external';
    }

    public function index(): array
    {
        if (empty($this->items)) {
            return [
                'success' => false,
                'message' => 'No external items provided for indexing.',
            ];
        }

        $current = ExternalSources::getAll();
        foreach ($current as $source) {
            if (!empty($source['link'])) {
                ExternalSources::remove((string) $source['link']);
            }
        }

        $added = 0;
        foreach ($this->items as $item) {
            $ok = ExternalSources::add(
                (string) ($item['title'] ?? ''),
                (string) ($item['link'] ?? ''),
                (string) ($item['context'] ?? '')
            );
            if ($ok) {
                $added++;
            }
        }

        return [
            'success' => true,
            'message' => 'External content indexed successfully.',
            'data' => [
                'indexed_count' => $added,
            ],
        ];
    }

    public function get(): array
    {
        return [
            'success' => true,
            'data' => ExternalSources::getAll(),
        ];
    }

    public function clear(): array
    {
        $current = ExternalSources::getAll();
        $cleared = 0;
        foreach ($current as $source) {
            if (!empty($source['link']) && ExternalSources::remove((string) $source['link'])) {
                $cleared++;
            }
        }

        return [
            'success' => true,
            'message' => 'External content cleared successfully.',
            'data' => [
                'cleared_count' => $cleared,
            ],
        ];
    }

    public function stats(): array
    {
        return [
            'total_count' => ExternalSources::count(),
        ];
    }
}
