<?php

declare(strict_types=1);

namespace App\Framework\Console\Analytics\Migrations;

use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\Migration\Migration;
use App\Framework\Database\Migration\MigrationVersion;
use App\Framework\Database\Schema\Blueprint;
use App\Framework\Database\Schema\Schema;

final readonly class CreateCommandUsageAnalyticsTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('command_usage_analytics', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('command_name', 255);
            $table->dateTime('executed_at');
            $table->decimal('execution_time_ms', 10, 3);
            $table->tinyInteger('exit_code')->default(0);
            $table->integer('argument_count')->default(0);
            $table->string('user_id', 255)->nullable();
            $table->json('metadata')->nullable();
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->useCurrent();

            $table->index('command_name', 'idx_command_name');
            $table->index('executed_at', 'idx_executed_at');
            $table->index('user_id', 'idx_user_id');
            $table->index(['command_name', 'executed_at'], 'idx_command_executed');
            $table->index(['command_name', 'exit_code'], 'idx_command_exit');
            $table->index(['executed_at', 'exit_code'], 'idx_executed_exit');

            $table->engine('InnoDB');
            $table->charset('utf8mb4');
            $table->collation('utf8mb4_unicode_ci');
        });

        $schema->execute();
    }

    public function down(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);
        $schema->dropIfExists('command_usage_analytics');
        $schema->execute();
    }

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromTimestamp('2024_01_01_000001');
    }

    public function getDescription(): string
    {
        return 'Create command_usage_analytics table for console command metrics';
    }
}
