<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\Migrations;

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

/**
 * Class Migration20260731100000
 *  spool table for out-of-band Sentry delivery
 *
 * @author tnt
 * @created Thu, 31 Jul 2026 10:00:00 +0100
 */
class Migration20260731100000 extends Migration implements IMigration
{
    protected $author      = 'tnt';
    protected $description = 'create stabila_shop_sentry_spool table for async Sentry delivery';

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

    public function getDescription(): string
    {
        return 'create stabila_shop_sentry_spool table for async Sentry delivery';
    }

    /**
     * @inheritdoc
     */
    public function up(): void
    {
        $this->execute('CREATE TABLE IF NOT EXISTS `stabila_shop_sentry_spool` (
            `id`         INT UNSIGNED NOT NULL AUTO_INCREMENT,
            `body`       LONGTEXT NOT NULL,
            `attempts`   INT UNSIGNED NOT NULL DEFAULT 0,
            `createDate` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `stabila_shop_sentry_spool_created_idx` (`createDate`)
            ) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');

        // Register the sending-only spool cron here (not only in installed()) so existing
        // installs also get it on update. frequency 0 = run on every cron tick. Idempotent so
        // re-running the migration never creates a duplicate.
        $this->execute("INSERT INTO `tcron` (`name`, `jobType`, `frequency`, `startDate`, `startTime`, `nextStart`)
            SELECT 'Stabila Sentry Spool', 'tnt_stabila_sentry_spool', 0, NOW(), '00:00:00', NOW()
            WHERE NOT EXISTS (SELECT 1 FROM `tcron` WHERE `jobType` = 'tnt_stabila_sentry_spool')");
    }

    /**
     * @inheritdoc
     */
    public function down(): void
    {
        $this->execute("DELETE FROM `tcron` WHERE `jobType` = 'tnt_stabila_sentry_spool'");
        $this->execute('DROP TABLE IF EXISTS `stabila_shop_sentry_spool`');
    }
}
