<?php

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

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

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

        DB::query(
            "CREATE TABLE IF NOT EXISTS `{$table}` (
                `id`             BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                `automation_id`  BIGINT UNSIGNED NOT NULL,
                `status`         VARCHAR(20)     NOT NULL DEFAULT 'pending',
                `trigger_data`   LONGTEXT        NULL,
                `result_data`    LONGTEXT        NULL,
                `error_message`  TEXT            NULL,
                `started_at`     TIMESTAMP       NULL,
                `completed_at`   TIMESTAMP       NULL,
                `created_at`     TIMESTAMP       NOT NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`),
                KEY `idx_automation_id` (`automation_id`),
                KEY `idx_status` (`status`),
                KEY `idx_created_at` (`created_at`)
            ) {$charset};"
        );
    }

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