<?php

namespace App\Console\Commands;

use App\Services\MicrosoftGraphSyncService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class DeleteMicrosoftGraphFoldersCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'msgraph:delete-folders
                            {--dry-run : Run in dry-run mode without making changes}
                            {--force : Skip confirmation prompts (DANGEROUS)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete ALL contact folders from Microsoft Graph (DESTRUCTIVE OPERATION)';

    protected $syncService;

    public function __construct(MicrosoftGraphSyncService $syncService)
    {
        parent::__construct();
        $this->syncService = $syncService;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->error('🚨 DESTRUCTIVE OPERATION WARNING 🚨');
        $this->warn('⚠️ This command will PERMANENTLY DELETE ALL contact folders from Microsoft Graph!');
        $this->warn('⚠️ This includes ALL contacts within those folders!');
        $this->warn('⚠️ This action CANNOT be undone!');
        $this->newLine();

        // Initialize the service - this will check if MS Graph is available
        if (!MicrosoftGraphSyncService::isAvailable()) {
            $this->error('❌ Microsoft Graph is not available. Please run migrations first.');
            return Command::FAILURE;
        }
        $this->syncService->initialize();

        if ($this->option('dry-run')) {
            $this->info('🧪 Running in DRY-RUN mode - no actual changes will be made');
        } else {
            $this->error('🔥 This is NOT a dry-run - folders will be PERMANENTLY DELETED!');
        }

        $this->newLine();

        // Safety checks and confirmations
        if (!$this->option('dry-run')) {
            if (!$this->option('force')) {
                // First confirmation
                if (!$this->confirm('Are you absolutely sure you want to DELETE ALL contact folders from Microsoft Graph?')) {
                    $this->info('❌ Operation cancelled by user');
                    return Command::SUCCESS;
                }

                // Second confirmation with typed confirmation
                $this->warn('⚠️ Last chance to cancel!');
                $confirmation = $this->ask('Type "DELETE ALL FOLDERS" to confirm this destructive operation');

                if ($confirmation !== 'DELETE ALL FOLDERS') {
                    $this->info('❌ Operation cancelled - confirmation text did not match');
                    return Command::SUCCESS;
                }

                $this->warn('🚨 Proceeding with folder deletion in 3 seconds...');
                sleep(3);
            } else {
                $this->warn('⚠️ Force flag detected - skipping confirmations');
            }
        }

        $startTime = microtime(true);

        try {
            $this->info('🗑️ Starting contact folder deletion process...');

            $results = $this->syncService->deleteAllContactFolders($this->option('dry-run'));

            $executionTime = round(microtime(true) - $startTime, 2);

            // Display results
            $this->newLine();
            $this->info('📊 Contact Folder Deletion Results:');
            $this->table(['Metric', 'Count'], [
                ['🗑️ Folders Deleted', $results['deleted_folders']],
                ['🏛️ Committees Cleaned', $results['committees_cleaned'] ?? 0],
                ['👨‍💼 Workgroups Cleaned', $results['workgroups_cleaned'] ?? 0],
                ['❌ Errors', $results['errors']]
            ]);

            $this->newLine();

            if ($this->option('dry-run')) {
                $this->info("🧪 DRY-RUN completed in {$executionTime} seconds");
                $this->info("💡 Run without --dry-run to actually delete the folders");
                $this->warn("⚠️ Remember: Real deletion is PERMANENT and cannot be undone!");
            } else {
                if ($results['deleted_folders'] > 0) {
                    $this->info("✅ Successfully deleted {$results['deleted_folders']} contact folders in {$executionTime} seconds");

                    $totalCleaned = ($results['committees_cleaned'] ?? 0) + ($results['workgroups_cleaned'] ?? 0);
                    if ($totalCleaned > 0) {
                        $this->info("🧹 Cleaned ms_id from {$results['committees_cleaned']} committees and {$results['workgroups_cleaned']} workgroups");
                    }

                    $this->info("💡 You can now run 'msgraph:sync' to recreate the folder structure");
                } else {
                    $this->info("📭 No contact folders found to delete");
                }
            }

            if ($results['errors'] > 0) {
                $this->warn("⚠️ {$results['errors']} errors occurred during the operation");
                $this->info("💡 Check the logs for details");
            }

            // Log the operation
            Log::info('Microsoft Graph contact folders deletion completed via artisan command', [
                'execution_time' => $executionTime,
                'results' => $results,
                'dry_run' => $this->option('dry-run'),
                'force' => $this->option('force')
            ]);

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $executionTime = round(microtime(true) - $startTime, 2);

            $this->error('❌ Contact folder deletion failed: ' . $e->getMessage());
            $this->warn("💥 Operation failed after {$executionTime} seconds");

            Log::error('Microsoft Graph contact folders deletion failed via artisan command', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'execution_time' => $executionTime,
                'dry_run' => $this->option('dry-run'),
                'force' => $this->option('force')
            ]);

            return Command::FAILURE;
        }
    }
}
