<?php

/**
 * Migration 057 – Create iw_marketplace_install_log table.
 *
 * Audit trail for every install/update/rollback attempt in the marketplace client.
 * Records verification result so security incidents can be forensically reconstructed.
 */

use App\Database\Migration;

class CreateMarketplaceInstallLog extends Migration
{
    public function up(): void
    {
        $this->db->query("
            CREATE TABLE IF NOT EXISTS iw_marketplace_install_log (
                id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                slug            VARCHAR(100)  NOT NULL,
                type            ENUM('plugin','theme') NOT NULL DEFAULT 'plugin',
                action          ENUM('install','update','rollback') NOT NULL DEFAULT 'install',
                version_target  VARCHAR(20)   NOT NULL DEFAULT '',
                registry_url    VARCHAR(500)  NOT NULL DEFAULT '',
                key_id          VARCHAR(32)   NOT NULL DEFAULT '',
                sha256_verified TINYINT(1)    NOT NULL DEFAULT 0,
                sig_verified    TINYINT(1)    NOT NULL DEFAULT 0,
                result          ENUM('success','failed','rolled_back') NOT NULL DEFAULT 'success',
                error_message   TEXT          NULL,
                backup_path     VARCHAR(500)  NULL,
                user_id         INT UNSIGNED  NULL,
                ip_address      VARCHAR(45)   NOT NULL DEFAULT '',
                created_at      DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_slug    (slug),
                INDEX idx_action  (action),
                INDEX idx_created (created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    public function down(): void
    {
        $this->db->query("DROP TABLE IF EXISTS iw_marketplace_install_log");
    }
}
