<?php
/**
 * Database installer.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Migration;

defined( 'ABSPATH' ) || exit;

/**
 * Creates plugin DB tables on activation.
 */
class Installer {

	private const DB_VERSION = '1.0.0';

	public function run(): void {
		if ( get_option( 'storesheet_db_version' ) === self::DB_VERSION ) {
			return;
		}

		$this->create_sync_log_table();
		$this->create_row_map_table();

		update_option( 'storesheet_db_version', self::DB_VERSION, false );
	}

	private function create_sync_log_table(): void {
		global $wpdb;

		$table   = $wpdb->prefix . 'storesheet_sync_log';
		$charset = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE {$table} (
			id           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			direction    ENUM('wc_to_sheets','sheets_to_wc') NOT NULL,
			resource     ENUM('product','variation','order','coupon','customer') NOT NULL,
			resource_id  BIGINT UNSIGNED NOT NULL,
			tab_name     VARCHAR(50)  NOT NULL DEFAULT '',
			row_index    INT UNSIGNED DEFAULT NULL,
			status       ENUM('pending','success','failed','skipped') NOT NULL DEFAULT 'pending',
			message      TEXT DEFAULT NULL,
			created_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY idx_resource   (resource, resource_id),
			KEY idx_status     (status),
			KEY idx_created_at (created_at)
		) {$charset};";

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

	private function create_row_map_table(): void {
		global $wpdb;

		$table   = $wpdb->prefix . 'storesheet_row_map';
		$charset = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE {$table} (
			id           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			tab_name     VARCHAR(50)  NOT NULL DEFAULT '',
			resource     VARCHAR(20)  NOT NULL DEFAULT '',
			resource_id  BIGINT UNSIGNED NOT NULL,
			row_index    INT UNSIGNED NOT NULL,
			sheet_id     VARCHAR(100) NOT NULL DEFAULT '',
			updated_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			UNIQUE KEY unique_resource (tab_name, resource, resource_id, sheet_id(50)),
			KEY idx_tab_row (tab_name, row_index)
		) {$charset};";

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