<?php

namespace RtmBusiness\PostSync\Migrations;

use Exception;
use RtmBusiness\PostSync\Model\Log;

/**
 * InitMigration - Initial SQL tables
 * Creates Logger SQL table
 */
class InitLoggerMigration implements MigrationInterface
{
    /**
     * @inheritDoc
     */
    public function migrate(): void
    {
        global $wpdb;

        $sql = "CREATE TABLE IF NOT EXISTS " . Log::getTable() . " (
                id int(11) NOT NULL AUTO_INCREMENT,
                title varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                message text COLLATE utf8mb4_unicode_ci NOT NULL,
                severity enum('error','info','warning','debug') COLLATE utf8mb4_unicode_ci NOT NULL,
                source varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                category varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                data longtext COLLATE utf8mb4_unicode_ci NOT NULL,
                metadata longtext CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
                timestamp datetime NOT NULL,
                 PRIMARY KEY (id)
            )" . $wpdb->get_charset_collate() . ";";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);

        if (!empty($wpdb->last_error)) {
            throw new Exception($wpdb->last_error);
        }
    }

    /**
     * @inheritDoc
     */
    public function rollback(): void
    {
        global $wpdb;
        $sql = "DROP TABLE " . Log::getTable() . ";";
        $wpdb->query($sql);
    }

    /**
     * @inheritDoc
     */
    public function isMigrated(): bool
    {
        global $wpdb;
        return ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", Log::getTable())) === Log::getTable());
    }

    /**
     * @inheritDoc
     */
    public function getPriority(): int
    {
        return 1;
    }
}
