<?php

namespace Database\Seeders;

use App\Models\Book;
use App\Models\Question;
use App\Models\Subject;
use Illuminate\Database\Seeder;

/**
 * Demo book profiles + curriculum question bank so the book profile and
 * question pages render populated: each book gets a grade/description and a
 * few chapters placed into months, each with easy/medium/hard questions.
 */
class BookQuestionsSeeder extends Seeder
{
    private array $monthsFa = [1 => 'حمل', 2 => 'ثور', 3 => 'جوزا', 4 => 'سرطان'];

    public function run(): void
    {
        $subjects = Subject::orderBy('id')->get();
        $books = Book::orderBy('id')->take(4)->get();
        foreach ($books as $bi => $book) {
            if ($book->chapters()->exists()) {
                continue; // idempotent
            }
            $grade = 7 + $bi;
            $book->update([
                'grade_level' => $grade,
                'subject_id' => $book->subject_id ?: optional($subjects[$bi] ?? null)->id,
                'description' => $book->description ?: "کتاب درسی {$book->title} — نشر {$book->publisher}.",
            ]);

            // 4 chapters across the first 4 months of grade $grade.
            foreach ([1, 2, 3, 4] as $month) {
                $chapter = $book->chapters()->create([
                    'year_level' => $grade,
                    'month' => $month,
                    'title' => "فصل {$month}: " . ($this->monthsFa[$month] ?? ''),
                    'sort_order' => $month,
                ]);

                foreach ([['easy', 2], ['easy', 2], ['medium', 3], ['medium', 3], ['hard', 5]] as $i => [$diff, $marks]) {
                    Question::create([
                        'book_chapter_id' => $chapter->id,
                        'topic' => $chapter->title,
                        'difficulty' => $diff,
                        'text' => ucfirst($diff) . " question " . ($i + 1) . " for {$chapter->title}",
                        'marks' => $marks,
                    ]);
                }
            }
        }

        $this->command?->info('Book question bank demo data seeded.');
    }
}
