<?php

namespace OtomaticAi\Database\Migrations;

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

        $thumbnail_tasks_table_name = $wpdb->prefix . "otomatic_ai_thumbnail_tasks";
        $publications_table_name = $wpdb->prefix . "otomatic_ai_publications";

        $sql = "CREATE TABLE IF NOT EXISTS `{$thumbnail_tasks_table_name}` (
        	`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            `publication_id` bigint(20) unsigned DEFAULT NULL,
            `model` varchar(255) NOT NULL,
            `override` tinyint(1) NOT NULL DEFAULT 0,
            `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}thumbnail_tasks_publication_id_foreign` (`publication_id`),
            CONSTRAINT `{$wpdb->prefix}thumbnail_tasks_publication_id_foreign` FOREIGN KEY (`publication_id`) REFERENCES `{$publications_table_name}` (`id`) ON DELETE CASCADE
          ) ENGINE=InnoDB {$charset_collate}";

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