<?php

declare(strict_types=1);

namespace BadamSoft\WooProductExporter\Scheduler;

use wpdb;

class Installer {
    private wpdb $db;

    public function __construct( wpdb $db ) {
        $this->db = $db;
    }

    public function install( bool $include_pro_tables = true ): void {
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $charset_collate = $this->db->get_charset_collate();
        $runs_table     = $this->db->prefix . 'prodexfo_export_runs';

        $sql_runs = "CREATE TABLE {$runs_table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            task_id BIGINT UNSIGNED NOT NULL,
            template_id VARCHAR(64) NOT NULL,
            run_type VARCHAR(20) NOT NULL DEFAULT 'scheduled',
            started_at DATETIME NOT NULL,
            finished_at DATETIME NULL DEFAULT NULL,
            status VARCHAR(20) NOT NULL,
            rows_exported BIGINT UNSIGNED NOT NULL DEFAULT 0,
            file_path TEXT NULL,
            fields_json LONGTEXT NULL,
            filters_json LONGTEXT NULL,
            settings_json LONGTEXT NULL,
            file_format VARCHAR(16) NOT NULL DEFAULT '',
            file_size BIGINT UNSIGNED NOT NULL DEFAULT 0,
            images_zip_path TEXT NULL,
            images_zip_size BIGINT UNSIGNED NOT NULL DEFAULT 0,
            actions LONGTEXT NULL,
            action_results LONGTEXT NULL,
            incremental_from DATETIME NULL DEFAULT NULL,
            incremental_to DATETIME NULL DEFAULT NULL,
            log LONGTEXT NULL,
            created_at DATETIME NULL DEFAULT NULL,
            PRIMARY KEY  (id),
            KEY task_id (task_id),
            KEY started_at (started_at)
        ) {$charset_collate};";

        unset( $include_pro_tables );

        \dbDelta( $sql_runs );
    }
}
