<?php

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

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

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

        DB::query(
            "CREATE TABLE IF NOT EXISTS `{$table}` (
                `id`           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                `name`         VARCHAR(255)    NOT NULL DEFAULT '',
                `platform`     VARCHAR(100)    NOT NULL,
                `auth_type`    VARCHAR(50)     NOT NULL DEFAULT 'api_key',
                `credentials`  LONGTEXT        NULL,
                `token_data`   LONGTEXT        NULL,
                `status`       VARCHAR(20)     NOT NULL DEFAULT 'active',
                `expires_at`   TIMESTAMP       NULL     DEFAULT 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_platform` (`platform`),
                KEY `idx_status` (`status`)
            ) {$charset};"
        );
    }

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