<?php

namespace OtomaticAi\Database\Migrations;

class CreateSingleModeGenerationsTableMigration 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();

        // single mode generations table
        $single_mode_generations_table_name = $wpdb->prefix . "otomatic_ai_single_mode_generations";
        $personas_table_name = $wpdb->prefix . "otomatic_ai_personas";

        $sql = "CREATE TABLE IF NOT EXISTS `{$single_mode_generations_table_name}` (
        	`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            `language` varchar(255) NOT NULL,
        	`type` varchar(255) NOT NULL,
            `title` text NOT NULL,
            `persona_id` bigint(20) unsigned DEFAULT NULL,
            `post_id` bigint(20) unsigned DEFAULT NULL,
            `status` varchar(255) DEFAULT 'idle',
            `settings` longtext DEFAULT NULL,
            `meta` longtext DEFAULT NULL,
            `logs` longtext DEFAULT NULL,
            `content` longtext DEFAULT NULL,
            `extras` longtext DEFAULT NULL,
        	`generated_at` datetime DEFAULT NULL,
        	`created_at` datetime DEFAULT NOW() NOT NULL,
        	`updated_at` datetime DEFAULT NOW() NOT NULL,
        	PRIMARY KEY  (`id`),
            KEY `{$wpdb->prefix}single_mode_generations_persona_id_foreign` (`persona_id`),
            CONSTRAINT `{$wpdb->prefix}single_mode_generations_persona_id_foreign` FOREIGN KEY (`persona_id`) REFERENCES `{$personas_table_name}` (`id`) ON DELETE SET NULL
          ) ENGINE=InnoDB {$charset_collate}";

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