<?php

namespace Database\Seeders;

use FluxCms\Core\Models\CmsSearchIndex;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class CmsSearchIndexSeeder extends Seeder
{
    public function run(): void
    {
        $deItems = $this->loadItems('de');
        $enItems = $this->loadItems('en');

        $deById = collect($deItems)->keyBy('id');
        $enById = collect($enItems)->keyBy('id');

        $allIds = $deById->keys()->merge($enById->keys())->unique();

        $order = 0;
        foreach ($allIds as $itemId) {
            $de = $deById->get($itemId, []);
            $en = $enById->get($itemId, []);
            $source = ! empty($de) ? $de : $en;

            CmsSearchIndex::updateOrCreate(
                ['item_id' => $itemId],
                [
                    'route' => $source['route'] ?? '',
                    'route_params' => $source['route_params'] ?? [],
                    'category' => [
                        'de' => $de['category'] ?? ($en['category'] ?? ''),
                        'en' => $en['category'] ?? ($de['category'] ?? ''),
                    ],
                    'title_key' => $source['title_key'] ?? null,
                    'title_fallback' => [
                        'de' => $de['title_fallback'] ?? null,
                        'en' => $en['title_fallback'] ?? null,
                    ],
                    'description_key' => $source['description_key'] ?? null,
                    'description_fallback_key' => $source['description_fallback_key'] ?? null,
                    'description_fallback_text' => [
                        'de' => $de['description_fallback_text'] ?? null,
                        'en' => $en['description_fallback_text'] ?? null,
                    ],
                    'keywords' => [
                        'de' => $de['keywords'] ?? [],
                        'en' => $en['keywords'] ?? [],
                    ],
                    'is_published' => true,
                    'order' => $order++,
                ]
            );
        }

        $this->command->info('CmsSearchIndexSeeder: '.$allIds->count().' Eintraege erstellt/aktualisiert.');
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    protected function loadItems(string $locale): array
    {
        $path = lang_path("{$locale}/search_index.php");
        if (! File::exists($path)) {
            return [];
        }

        $config = require $path;

        return $config['items'] ?? [];
    }
}
