<?php

use EasyLinkAutomations\Config;
use EasyLinkAutomations\Database\Connection as DB;
use EasyLinkAutomations\Migration\Migration;

if (!defined('ABSPATH')) {
    exit;
}

final class EasyLinkAutomationsAutomationActionsTableMigration extends Migration
{
    public function up(): void
    {
        global $wpdb;
        $charset         = $wpdb->get_charset_collate();
        $table           = Config::withDBPrefix('automation_actions');
        $automationsTable = Config::withDBPrefix('automations');

        DB::query(
            "CREATE TABLE IF NOT EXISTS `{$table}` (
                `id`             BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                `automation_id`  BIGINT UNSIGNED NOT NULL,
                `action_slug`    VARCHAR(255)    NOT NULL,
                `config`         LONGTEXT        NULL,
                `action_order`   INT             NOT NULL DEFAULT 0,
                `created_at`     TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `updated_at`     TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`),
                KEY `idx_automation_id` (`automation_id`),
                CONSTRAINT `fk_easylink_automations_aa_automation_id` 
                    FOREIGN KEY (`automation_id`) 
                    REFERENCES `{$automationsTable}` (`id`) 
                    ON DELETE CASCADE 
                    ON UPDATE CASCADE
            ) {$charset};"
        );
    }

    public function down(): void
    {
        $table = Config::withDBPrefix('automation_actions');
        DB::query("DROP TABLE IF EXISTS `{$table}`");
    }
}
