<?php

namespace Database\Seeders;

use App\Models\Faq;
use Illuminate\Database\Seeder;

class FaqContentSeeder extends Seeder
{
    /**
     * Seed FAQs from parsed docx articles.
     * Source: storage/app/parsed_faqs.json
     * Uses firstOrCreate (question-based) — safe to re-run.
     */
    public function run(): void
    {
        $jsonPath = storage_path('app/parsed_faqs.json');

        if (! file_exists($jsonPath)) {
            $this->command->error('parsed_faqs.json bulunamadı. Önce Python parse script çalıştırın.');

            return;
        }

        /** @var array<int, array{question: string, answer: string, source: string}> $faqs */
        $faqs = json_decode(file_get_contents($jsonPath), true);

        $categoryMap = [
            'Guverte_Egitimleri' => 'egitimler',
            'STCW_Egitimleri' => 'stcw',
            'Makine_Egitimleri' => 'makine',
            'Yat_Kaptanligi_Egitimleri' => 'yat-kaptanligi',
            'Yenileme_Egitimleri' => 'yenileme',
            'Seminer_Sertifikalari' => 'guvenlik',
        ];

        $created = 0;
        $skipped = 0;
        $orderCounters = [];

        foreach ($faqs as $faq) {
            // Determine category from source folder
            $sourceFolder = explode('/', $faq['source'])[0] ?? '';
            $category = $categoryMap[$sourceFolder] ?? 'egitimler';

            // Track order per category
            $orderCounters[$category] = ($orderCounters[$category] ?? -1) + 1;

            $result = Faq::firstOrCreate(
                ['question' => $faq['question']],
                [
                    'category' => $category,
                    'answer' => $faq['answer'],
                    'order_index' => $orderCounters[$category],
                    'is_active' => true,
                ],
            );

            if ($result->wasRecentlyCreated) {
                $created++;
            } else {
                $skipped++;
            }
        }

        $this->command->info("FAQ: {$created} oluşturuldu, {$skipped} zaten mevcuttu.");
    }
}
