<?php

declare(strict_types=1);

namespace App\Framework\Database\Monitoring\Commands;

use App\Framework\Console\ConsoleCommand;
use App\Framework\Console\ExitCode;
use App\Framework\Database\Monitoring\History\QueryHistoryLogger;

/**
 * Command to log query statistics to the history tables
 */
final readonly class LogQueryStatisticsCommand
{
    public function __construct(
        private QueryHistoryLogger $historyLogger
    ) {
    }

    /**
     * Log current query statistics to the history tables
     *
     * @return ExitCode
     */
    #[ConsoleCommand('db:log-stats', 'Log current query statistics to the history tables')]
    public function __invoke(): ExitCode
    {
        try {
            $this->historyLogger->logCurrentStats();
            echo "Query statistics logged successfully.\n";

            return ExitCode::SUCCESS;
        } catch (\Throwable $e) {
            echo "Error logging query statistics: {$e->getMessage()}\n";

            return ExitCode::SOFTWARE_ERROR;
        }
    }

    /**
     * Purge old query statistics data
     *
     * @param int $days Number of days of history to keep
     * @return ExitCode
     */
    #[ConsoleCommand('db:purge-stats', 'Purge old query statistics data')]
    public function purge(int $days = 30): ExitCode
    {
        try {
            $deleted = $this->historyLogger->purgeOldData($days);
            echo "Purged {$deleted} records older than {$days} days.\n";

            return ExitCode::SUCCESS;
        } catch (\Throwable $e) {
            echo "Error purging query statistics: {$e->getMessage()}\n";

            return ExitCode::SOFTWARE_ERROR;
        }
    }
}
