<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Modules\Language\Models\Language;
use Modules\Language\Models\LanguageProperty;

class ImportDeLanguageSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $langCode = 'de';

        $language = Language::firstOrCreate(
            ['code' => $langCode],
            [
                'name' => 'German',
                'nativeName' => 'Deutsch',
                'is_active' => true,
                'is_default' => false,
            ]
        );

        $groupsDir = storage_path('app/lang/groups/de');
        if (!is_dir($groupsDir)) {
            $this->command->info("No groups directory found at $groupsDir — skipping import.");
            return;
        }

        $files = glob($groupsDir.'/*.php');
        foreach ($files as $file) {
            $groupKey = basename($file, '.php');
            $entries = require $file;
            if (!is_array($entries)) continue;

            foreach ($entries as $entry) {
                if (!isset($entry['slug'])) continue;

                LanguageProperty::updateOrCreate(
                    ['slug' => $entry['slug'], 'language_id' => $language->id],
                    array_merge($entry, ['group' => $groupKey, 'language_id' => $language->id])
                );
            }
        }

        $this->command->info('ImportDeLanguageSeeder: import complete.');
    }
}
