<?php

declare(strict_types=1);

namespace App\Infrastructure\Database\Migrations;

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

/**
 * Create component_state table for LiveComponents state persistence
 *
 * Stores current state of LiveComponents with metadata and tracking.
 * NOT reversible: Production table with user data - no safe rollback.
 */
final readonly class CreateComponentStateTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->create('component_state', function ($table) {
            // Primary Key
            $table->string('component_id', 255)->primary();

            // State Data (encrypted)
            $table->text('state_data');
            $table->string('state_class', 255);

            // Metadata
            $table->string('component_name', 255);
            $table->string('user_id', 255)->nullable();
            $table->string('session_id', 255)->nullable();

            // Tracking
            $table->unsignedInteger('version')->default(1);
            $table->string('checksum', 64); // SHA256

            // Timestamps
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
            $table->timestamp('expires_at')->nullable();

            // Indexes for performance
            $table->index('component_name', 'idx_component_state_name');
            $table->index('user_id', 'idx_component_state_user');
            $table->index('session_id', 'idx_component_state_session');
            $table->index('expires_at', 'idx_component_state_expires');
            $table->index('updated_at', 'idx_component_state_updated');
        });

        $schema->execute();
    }

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromString('2024_12_20_120000');
    }

    public function getDescription(): string
    {
        return 'Create component_state table for LiveComponents persistence';
    }
}
