<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Quiz;
use App\Models\QuizQuestion;
use App\Models\Book;
use App\Models\User;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class QuizDiagnostic extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'quizzes:diagnostic';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Diagnose quiz system issues';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('=== QUIZ SYSTEM DIAGNOSTIC ===');
        $this->newLine();

        // Check if tables exist
        $this->info('1. Checking Database Tables...');
        $tables = [
            'quizzes' => 'quizzes',
            'quiz_questions' => 'quiz_questions',
            'quiz_answers' => 'quiz_answers',
            'quiz_attempts' => 'quiz_attempts',
            'quiz_attempt_answers' => 'quiz_attempt_answers',
            'question_bookmarks' => 'question_bookmarks',
        ];

        $allTablesExist = true;
        foreach ($tables as $name => $table) {
            $exists = Schema::hasTable($table);
            $status = $exists ? '✓ EXISTS' : '✗ MISSING';
            $this->line("   {$name}: {$status}");
            if (!$exists) {
                $allTablesExist = false;
            }
        }

        if (!$allTablesExist) {
            $this->error('Some tables are missing! Run migrations first:');
            $this->line('   php artisan migrate --force');
            return 1;
        }

        $this->newLine();

        // Check data
        $this->info('2. Checking Data...');
        $quizCount = Quiz::count();
        $questionCount = QuizQuestion::count();
        $answerCount = DB::table('quiz_answers')->count();
        
        $this->line("   Quizzes: {$quizCount}");
        $this->line("   Questions: {$questionCount}");
        $this->line("   Answers: {$answerCount}");

        if ($quizCount == 0) {
            $this->newLine();
            $this->warn('No quizzes found in database!');
            
            // Check prerequisites
            $this->info('3. Checking Prerequisites for Seeder...');
            $admin = User::where('role', 'admin')->first();
            $book = Book::where('title', 'like', '%Flutter%')->first();
            
            $this->line("   Admin user: " . ($admin ? "✓ Found (ID: {$admin->id})" : "✗ Not found"));
            $this->line("   Flutter book: " . ($book ? "✓ Found (ID: {$book->id})" : "✗ Not found"));
            
            $this->newLine();
            $this->info('To create quizzes, run:');
            $this->line('   php artisan db:seed --class=QuizSeeder');
            
            if (!$admin) {
                $this->warn('   WARNING: No admin user found. Seeder may fail.');
            }
            if (!$book) {
                $this->warn('   WARNING: No Flutter book found. Quizzes will be created without book_id.');
            }
        } else {
            $this->newLine();
            $this->info('4. Quiz Details:');
            Quiz::with('questions')->get()->each(function($quiz) {
                $active = $quiz->is_active ? '✓ Active' : '✗ Inactive';
                $this->line("   [{$quiz->id}] {$quiz->title} - {$active} - {$quiz->questions->count()} questions");
            });
        }

        $this->newLine();
        $this->info('=== DIAGNOSTIC COMPLETE ===');
        
        return 0;
    }
}

