<?php

namespace OtomaticAi\Database\Migrations;

class CreateNetlinkingTableMigration extends Migration
{
    /**
     * Run a new migration
     *
     * @return void
     */
    public function run()
    {
        global $wpdb;

        if (!$this->canRun()) {
            return;
        }

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

        $charset_collate = $wpdb->get_charset_collate();

        $personas_table_name = $wpdb->prefix . "otomatic_ai_personas";
        $netlinking_table_name = $wpdb->prefix . "otomatic_ai_netlinking";

        $sql = "CREATE TABLE IF NOT EXISTS `{$netlinking_table_name}` (
        	`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            `uuid` varchar(255) NOT NULL,
            `title` text NOT NULL,
            `language` varchar(255) NOT NULL,
            `target_url` varchar(255) NOT NULL,
            `anchor_text` varchar(255) DEFAULT NULL,
            `modules` longtext DEFAULT NULL,
            `persona_id` bigint(20) unsigned DEFAULT NULL,
            `post_id` bigint(20) unsigned DEFAULT NULL,
            `status` varchar(255) DEFAULT 'idle' NOT NULL,
            `logs` longtext DEFAULT NULL,
        	`created_at` datetime DEFAULT NOW() NOT NULL,
        	`updated_at` datetime DEFAULT NOW() NOT NULL,
        	PRIMARY KEY  (`id`),
            KEY `{$wpdb->prefix}netlinking_persona_id_foreign` (`persona_id`),
            CONSTRAINT `{$wpdb->prefix}netlinking_persona_id_foreign` FOREIGN KEY (`persona_id`) REFERENCES `{$personas_table_name}` (`id`) ON DELETE SET NULL
          ) ENGINE=InnoDB {$charset_collate}";

        $out = \dbDelta($sql);
    }
}
