<?php

namespace App\Console\Commands;

use Database\Seeders\ComprehensiveSeeder;
use Database\Seeders\DevelopmentSeeder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SeedComprehensiveData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'seed:comprehensive 
                            {--comprehensive : Run the comprehensive seeder with extensive data}
                            {--development : Run the development seeder with factory-based data}
                            {--all : Run both comprehensive and development seeders}
                            {--fresh : Run fresh migration before seeding}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Seed comprehensive test data for development and testing';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🚀 Starting comprehensive data seeding...');

        // Check if fresh migration is requested
        if ($this->option('fresh')) {
            $this->info('🔄 Running fresh migrations...');
            $this->call('migrate:fresh');
        }

        // Run essential seeders first if tables are empty
        $this->ensureEssentialData();

        try {
            DB::transaction(function () {
                if ($this->option('all')) {
                    $this->runAllSeeders();
                } elseif ($this->option('comprehensive')) {
                    $this->runComprehensiveSeeder();
                } elseif ($this->option('development')) {
                    $this->runDevelopmentSeeder();
                } else {
                    // Interactive mode
                    $this->runInteractiveMode();
                }
            });

            $this->newLine();
            $this->info('✅ Comprehensive seeding completed successfully!');
            $this->displaySeededDataSummary();
        } catch (\Exception $e) {
            $this->error('❌ Seeding failed: '.$e->getMessage());
            $this->error('Stack trace: '.$e->getTraceAsString());

            return Command::FAILURE;
        }

        return Command::SUCCESS;
    }

    /**
     * Ensure essential data is present
     */
    private function ensureEssentialData(): void
    {
        $this->info('📋 Checking essential data...');

        $essentialSeeders = [
            'Database\Seeders\LocationSeeder',
            'Database\Seeders\SekayaValueSeeder',
            'Database\Seeders\RoleSeeder',
            'Database\Seeders\UserSeeder',
            'Database\Seeders\DonorFinancialPortfolioSeeder',
        ];

        // Check if we need to run essential seeders
        $needsEssentialData = false;

        if (DB::table('users')->count() === 0) {
            $needsEssentialData = true;
        }

        if ($needsEssentialData) {
            $this->info('⚡ Running essential seeders...');
            foreach ($essentialSeeders as $seeder) {
                $this->call('db:seed', ['--class' => $seeder]);
            }
        } else {
            $this->info('✓ Essential data already present');
        }
    }

    /**
     * Run interactive mode
     */
    private function runInteractiveMode(): void
    {
        $this->info('🎮 Interactive seeding mode');

        $choices = [
            'comprehensive' => 'Comprehensive Seeder (Extensive test data with all scenarios)',
            'development' => 'Development Seeder (Factory-based realistic data)',
            'both' => 'Both seeders (Maximum test coverage)',
            'cancel' => 'Cancel seeding',
        ];

        $choice = $this->choice('Which seeder would you like to run?', array_values($choices), 0);

        switch (array_search($choice, $choices)) {
            case 'comprehensive':
                $this->runComprehensiveSeeder();
                break;
            case 'development':
                $this->runDevelopmentSeeder();
                break;
            case 'both':
                $this->runAllSeeders();
                break;
            case 'cancel':
                $this->info('🚫 Seeding cancelled');

                return;
        }
    }

    /**
     * Run comprehensive seeder
     */
    private function runComprehensiveSeeder(): void
    {
        $this->info('🎯 Running comprehensive seeder...');
        $seeder = new ComprehensiveSeeder;
        $seeder->setCommand($this);
        $seeder->run();
    }

    /**
     * Run development seeder
     */
    private function runDevelopmentSeeder(): void
    {
        $this->info('🏭 Running development seeder...');
        $seeder = new DevelopmentSeeder;
        $seeder->setCommand($this);
        $seeder->run();
    }

    /**
     * Run all seeders
     */
    private function runAllSeeders(): void
    {
        $this->info('🌟 Running all comprehensive seeders...');
        $this->runComprehensiveSeeder();
        $this->runDevelopmentSeeder();
    }

    /**
     * Display summary of seeded data
     */
    private function displaySeededDataSummary(): void
    {
        $this->newLine();
        $this->info('📊 Seeded Data Summary:');
        $this->table(
            ['Entity', 'Count'],
            [
                ['Users', DB::table('users')->count()],
                ['Associations', DB::table('associations')->count()],
                ['Orders', DB::table('orders')->count()],
                ['Order Requirements', DB::table('order_requirements')->count()],
                ['Order Finances', DB::table('order_finances')->count()],
                ['Order Agreements', DB::table('order_agreements')->count()],
                ['Performance Cards', DB::table('performance_cards')->count()],
                ['Performance Wallets', DB::table('performance_wallets')->count()],
                ['Initiatives', DB::table('initiatives')->count()],
                ['Initiative Projects', DB::table('initiative_projects')->count()],
                ['Project Charters', DB::table('project_charters')->count()],
                ['Operation Goals', DB::table('initiative_operation_goals')->count()],
                ['Initiative Results', DB::table('initiative_results')->count()],
                ['Donor Portfolios', DB::table('donor_financial_portfolios')->count()],
                ['States', DB::table('states')->count()],
                ['Cities', DB::table('cities')->count()],
                ['Centers', DB::table('centers')->count()],
            ]
        );

        $this->newLine();
        $this->info('🔗 Useful Commands:');
        $this->line('• View seeded data: php artisan tinker');
        $this->line('• Reset and reseed: php artisan seed:comprehensive --fresh --all');
        $this->line('• Check application: php artisan serve');
    }
}
