<?php

/**
 * create the one-time setup links handed out by begin_ai_key_entry
 *
 * @author tnt
 * @created Wed, 05 Aug 2026 23:00:00 +0100
 */

declare(strict_types=1);

namespace Plugin\tnt_mcp\Migrations;

use JTL\Plugin\Migration;
use JTL\Update\IMigration;

/**
 * Class Migration_20260805230000
 *
 * `tnt_mcp_ai_setup_token` — the short-lived, single-use links an MCP client creates so the merchant
 * can type their API key into the shop admin rather than into a chat window.
 *
 * ## Why a table and not the change journal
 *
 * The journal records what happened; this row has to be *spent*, and spending is a conditional
 * UPDATE on a unique key. A UNIQUE index on the hash is what makes "use it once" a database
 * guarantee rather than a race between two browser tabs.
 *
 * Only the SHA-256 of the token is stored — see {@see \Plugin\tnt_mcp\src\Ai\AiSetupTokenStore} for
 * why, and for why a token is nevertheless not a credential.
 *
 * `down()` DROPs the table: a pending setup link is worth nothing after an uninstall.
 */
class Migration20260805230000 extends Migration implements IMigration
{
    protected $author = 'tnt';
    // For backwards compatibility, the description property cant be strictly typed as a string
    protected $description = 'create the AI setup-link table';

    public function getAuthor(): ?string
    {
        return 'tnt';
    }

    public function getDescription(): string
    {
        return 'create the AI setup-link table';
    }

    /**
     * @inheritdoc
     */
    public function up(): void
    {
        $this->execute("CREATE TABLE IF NOT EXISTS `tnt_mcp_ai_setup_token` (
              `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
              `tokenHash` CHAR(64) NOT NULL,
              `createdAt` DATETIME NOT NULL,
              `expiresAt` DATETIME NOT NULL,
              `usedAt` DATETIME NULL DEFAULT NULL,
              `createdBy` VARCHAR(64) NOT NULL DEFAULT '',
              PRIMARY KEY (`id`),
              UNIQUE KEY `tokenHash` (`tokenHash`)
            ) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    }

    /**
     * @inheritdoc
     */
    public function down(): void
    {
        $this->execute('DROP TABLE IF EXISTS `tnt_mcp_ai_setup_token`');
    }
}
