<?php

declare(strict_types=1);

namespace App\Framework\Database\Commands;

use App\Framework\Console\ConsoleCommand;
use App\Framework\Console\ConsoleInput;
use App\Framework\Console\ConsoleOutput;
use App\Framework\Console\ConsoleStyle;
use App\Framework\Console\ExitCode;
use App\Framework\Database\DatabaseManager;
use App\Framework\Database\EntityManager;
use App\Framework\Database\Profiling\ProfilingDashboard;

final class ClearProfilingDataCommand
{
    public function __construct(
        private DatabaseManager $databaseManager,
        private EntityManager $entityManager
    ) {
    }

    #[ConsoleCommand(name: 'db:profiling:clear', description: 'Clear all database profiling data and statistics')]
    public function execute(ConsoleInput $input, ConsoleOutput $output): ExitCode
    {
        $output->writeLine("🧹 Clearing Database Profiling Data\n", ConsoleStyle::info());

        // Check if profiling is enabled
        if (! $this->databaseManager->isProfilingEnabled()) {
            $output->writeLine("⚠️  Database profiling is not enabled", ConsoleStyle::warning());

            return ExitCode::SUCCESS;
        }

        // Clear data from EntityManager
        $this->entityManager->clearProfilingData();
        $output->writeLine("✅ Cleared profiling data from EntityManager", ConsoleStyle::success());

        // Create dashboard and clear all data
        $dashboard = new ProfilingDashboard();
        $this->databaseManager->registerWithProfilingDashboard($dashboard, 'main');

        $dashboard->clearAllProfilingData();
        $output->writeLine("✅ Cleared profiling data from all registered connections", ConsoleStyle::success());

        $output->writeLine("\n🎉 All profiling data has been cleared!", ConsoleStyle::success());

        return ExitCode::SUCCESS;
    }
}
