<?php

namespace App\Console\Commands\Migrations;

use Illuminate\Console\Command;

class MigrationManager
{
    protected Command $command;

    protected string $connection;

    protected array $migrations = [];

    protected array $allStats = [];

    public function __construct(Command $command, string $connection)
    {
        $this->command = $command;
        $this->connection = $connection;
    }

    /**
     * Register a migration
     */
    public function register(string $key, BaseMigration $migration): void
    {
        $this->migrations[$key] = $migration;
    }

    /**
     * Get a specific migration
     */
    public function getMigration(string $key): ?BaseMigration
    {
        return $this->migrations[$key] ?? null;
    }

    /**
     * Get all registered migrations
     */
    public function getMigrations(): array
    {
        return $this->migrations;
    }

    /**
     * Run a specific migration
     */
    public function runMigration(string $key, bool $dryRun, int $batchSize, int $startFrom): bool
    {
        if (! isset($this->migrations[$key])) {
            $this->command->error("❌ Migration '{$key}' not found");

            return false;
        }

        $migration = $this->migrations[$key];

        try {
            $migration->migrate($dryRun, $batchSize, $startFrom);
            $this->allStats[$key] = $migration->getStats();

            return true;
        } catch (\Exception $e) {
            $this->command->error("❌ Migration '{$key}' failed: ".$e->getMessage());

            return false;
        }
    }

    /**
     * Run all migrations in order
     */
    public function runAll(bool $dryRun, int $batchSize, int $startFrom): bool
    {
        $success = true;

        foreach ($this->migrations as $key => $migration) {
            if (! $this->runMigration($key, $dryRun, $batchSize, $startFrom)) {
                $success = false;
                break; // Stop on first failure
            }
        }

        return $success;
    }

    /**
     * Display results for all migrations
     */
    public function displayResults(bool $dryRun): void
    {
        $this->command->newLine();
        $this->command->info('📊 Migration Results:');
        $this->command->newLine();

        foreach ($this->allStats as $key => $stats) {
            $migrationName = ucfirst($key);
            $this->command->info("👥 {$migrationName}:");
            $this->command->info("   Total: {$stats['total']}");
            $this->command->info("   Migrated: {$stats['migrated']}");
            $this->command->info("   Skipped: {$stats['skipped']}");
            $this->command->info("   Errors: {$stats['errors']}");
            $this->command->newLine();
        }

        if (! $dryRun) {
            // Get default password from user migration if available
            $userMigration = $this->getMigration('users');
            if ($userMigration instanceof UserMigration) {
                $defaultPassword = $userMigration->getDefaultPassword();
                $this->command->warn("🔐 All migrated users have the default password: {$defaultPassword}");
                $this->command->warn('⚠️  Please ensure users change their passwords on first login');
            }
            $this->command->info('📁 Files (logos, photos) require manual migration');
        }
    }

    /**
     * Get combined statistics for all migrations
     */
    public function getAllStats(): array
    {
        return $this->allStats;
    }
}
