<?php

namespace Database\Seeders;

use App\Models\Card;
use App\Models\Course;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CourseSeeder extends Seeder
{
    private const DESCRIPTIONS = [
        'dev-web' => 'HTML, CSS, JavaScript, PHP, API REST et sécurité — tous les fondamentaux du développement web côté client et serveur.',
        'dev-mobile-rest' => 'Kotlin, Android & Jetpack Compose, puis les services web REST en Java (JAX-RS, Quarkus) — du mobile à l’API.',
    ];

    public function run(): void
    {
        $path = database_path('data/courses.json');
        $data = json_decode(file_get_contents($path), true, flags: JSON_THROW_ON_ERROR);

        DB::transaction(function () use ($data) {
            foreach ($data as $courseData) {
                $course = Course::create([
                    'slug' => $courseData['slug'],
                    'name' => $courseData['name'],
                    'emoji' => $courseData['emoji'] ?? null,
                    'description' => self::DESCRIPTIONS[$courseData['slug']] ?? null,
                    'position' => $courseData['order'] ?? 0,
                ]);

                foreach ($courseData['chapters'] as $chapterData) {
                    $chapter = $course->chapters()->create([
                        'slug' => $chapterData['slug'],
                        'name' => $chapterData['name'],
                        'emoji' => $chapterData['emoji'] ?? null,
                        'position' => $chapterData['order'] ?? 0,
                    ]);

                    $position = 0;
                    $rows = [];
                    foreach ($chapterData['cards'] as $cardData) {
                        $rows[] = [
                            'chapter_id' => $chapter->id,
                            'term' => $cardData['term'],
                            'definition' => $cardData['definition'],
                            'example' => $cardData['example'] ?? null,
                            'position' => $position++,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ];
                    }

                    foreach (array_chunk($rows, 200) as $chunk) {
                        Card::insert($chunk);
                    }
                }
            }
        });

        $this->command?->info('Seeded '.Course::count().' courses, '.\App\Models\Chapter::count().' chapters, '.Card::count().' cards.');
    }
}
