<?php

namespace CelerSearch\Database;

class Setup {

	/**
	 * List of migrations
	 * @var int[]
	 */
	public static $migrations = [
		100,
		101,
		102
	];

	/**
	 * Run schema
	 */
	public static function migrate() {
		$db_version = get_option('celersearch_db_version', 0);
		$latest_version = static::$migrations[count(static::$migrations) - 1];
		if($db_version < $latest_version) {
			foreach(self::$migrations as $migration) {
				if($migration > $db_version) {
					if(method_exists(static::class, 'migration_'.$migration)) {
						call_user_func([static::class, 'migration_'.$migration]);
						$db_version = $migration;
						update_option('celersearch_db_version', $db_version);
					}
				}
			}
		}
	}

	/**
	 * Implementation of the specific migration
	 * @return void
	 */
	public static function migration_100() {

		global $wpdb;

		$tbl_indices = $wpdb->prefix . 'celersearch_indices';
		$tbl_services = $wpdb->prefix . 'celersearch_services';

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

		dbDelta(
			"CREATE TABLE IF NOT EXISTS $tbl_indices (
                `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
	    		`name` VARCHAR(200) NOT NULL,
    			`type` VARCHAR(200) NOT NULL,
        		`slug` VARCHAR(200) NOT NULL UNIQUE,
    			`service_id` BIGINT(20) UNSIGNED NULL,
                `config` LONGTEXT NULL,
                `total_remote` BIGINT(20) UNSIGNED NULL,
                `total_local` BIGINT(20) UNSIGNED NULL,
                `status` VARCHAR(200) NULL,
    			`checked_at` DATETIME NULL,
    			`synced_at` DATETIME NULL,
    			`created_at` DATETIME NULL,
                PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
		);

		dbDelta(
			"CREATE TABLE IF NOT EXISTS $tbl_services (
                `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    			`name` VARCHAR(200) NOT NULL,
        		`provider` VARCHAR(200) NOT NULL,
                `config` LONGTEXT NOT NULL,
        		`status` VARCHAR(200) NULL,
                `checked_at` DATETIME NULL,
    			`created_at` DATETIME NULL,
                PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
		);
	}

	/**
	 * Migration 101: Add failure_count column to services table
	 * @return void
	 */
	public static function migration_101() {
		global $wpdb;
		$table = $wpdb->prefix . 'celersearch_services';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Migration for custom table
		$wpdb->query( "ALTER TABLE $table ADD COLUMN failure_count INT DEFAULT 0" );
	}

	/**
	 * Migration 102: Add views table for saved search view configurations
	 * @return void
	 */
	public static function migration_102() {
		global $wpdb;

		$tbl_views = $wpdb->prefix . 'celersearch_views';

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

		dbDelta(
			"CREATE TABLE IF NOT EXISTS $tbl_views (
				`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				`name` VARCHAR(255) NOT NULL,
				`type` VARCHAR(50) NOT NULL DEFAULT 'search',
				`index_id` BIGINT(20) UNSIGNED NOT NULL,
				`config` TEXT NOT NULL,
				`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
				`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
				PRIMARY KEY (`id`),
				KEY `idx_type` (`type`)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
		);
	}

}