<?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\Profiling\ProfilingDashboard;

final class ExportProfilingDataCommand
{
    public function __construct(
        private DatabaseManager $databaseManager
    ) {
    }

    #[ConsoleCommand(name: 'db:profiling:export', description: 'Export database profiling data to various formats (json, html)')]
    public function execute(ConsoleInput $input, ConsoleOutput $output): ExitCode
    {
        // Check if profiling is enabled
        if (! $this->databaseManager->isProfilingEnabled()) {
            $output->writeLine("⚠️  Database profiling is not enabled", ConsoleStyle::warning());

            return ExitCode::SUCCESS;
        }

        // Get format parameter (default: json)
        $format = $input->getOption('format', 'json');
        $connectionName = $input->getOption('connection');

        if (! in_array($format, ['json', 'html'])) {
            $output->writeLine("❌ Invalid format '{$format}'. Supported formats: json, html", ConsoleStyle::error());

            return ExitCode::FAILURE;
        }

        // Create dashboard and register connection
        $dashboard = new ProfilingDashboard();
        $this->databaseManager->registerWithProfilingDashboard($dashboard, $connectionName ?? 'main');

        try {
            $exportData = $dashboard->export($format, $connectionName);

            if ($format === 'html') {
                $output->writeLine("📄 Database Profiling Report (HTML Format)\n", ConsoleStyle::info());
            } else {
                $output->writeLine("📊 Database Profiling Data (JSON Format)\n", ConsoleStyle::info());
            }

            // Output the exported data
            $output->write($exportData);

        } catch (\Exception $e) {
            $output->writeLine("❌ Export failed: " . $e->getMessage(), ConsoleStyle::error());

            return ExitCode::FAILURE;
        }

        return ExitCode::SUCCESS;
    }
}
