<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\Migrations;

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

/**
 * Creates the two tables the MCP server needs:
 *  - tnt_mcp_token: per-shop bearer tokens (stored ONLY as a sha256 hash), their granted
 *    scopes (JSON array) and active flag. Deny-by-default: no matching active row => rejected.
 *  - tnt_mcp_audit: append-only log of every MCP call (token, tool, args, outcome, time).
 */
class Migration20260723000000 extends Migration implements IMigration
{
    public function up(): void
    {
        $this->execute("CREATE TABLE IF NOT EXISTS `tnt_mcp_token` (
                `kToken` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
                `cLabel` VARCHAR(191) NOT NULL DEFAULT '',
                `cTokenHash` CHAR(64) NOT NULL,
                `cScopes` TEXT NOT NULL,
                `nActive` TINYINT(1) NOT NULL DEFAULT 1,
                `dCreated` DATETIME NOT NULL,
                `dLastUsed` DATETIME NULL DEFAULT NULL,
                PRIMARY KEY (`kToken`),
                UNIQUE KEY `idx_tnt_mcp_token_hash` (`cTokenHash`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        $this->execute("CREATE TABLE IF NOT EXISTS `tnt_mcp_audit` (
                `kAudit` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                `cTokenId` VARCHAR(191) NOT NULL DEFAULT '',
                `cTool` VARCHAR(191) NOT NULL DEFAULT '',
                `cArgs` MEDIUMTEXT NOT NULL,
                `cOutcome` VARCHAR(64) NOT NULL DEFAULT '',
                `dCreated` DATETIME NOT NULL,
                PRIMARY KEY (`kAudit`),
                KEY `idx_tnt_mcp_audit_created` (`dCreated`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    }

    public function down(): void
    {
        $this->execute('DROP TABLE IF EXISTS `tnt_mcp_audit`');
        $this->execute('DROP TABLE IF EXISTS `tnt_mcp_token`');
    }
}
