<?php

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

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

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

        DB::query(
            "CREATE TABLE IF NOT EXISTS `{$table}` (
                `id`          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                `title`       VARCHAR(255)    NOT NULL DEFAULT '',
                `description` TEXT            NULL,
                `status`      VARCHAR(20)     NOT NULL DEFAULT 'draft',
                `trigger_type` VARCHAR(100)   NULL,
                `trigger_data` LONGTEXT       NULL,
                `config`      LONGTEXT        NULL,
                `created_by`  BIGINT UNSIGNED NULL,
                `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_status` (`status`),
                KEY `idx_trigger_type` (`trigger_type`)
            ) {$charset};"
        );
    }

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