<?php

namespace SugarCalendarBookings\Integrations\ExternalBusyTimes;

use SugarCalendarBookings\Support\Database\AbstractTableMigration;
use WP_Error;

/**
 * External busy times table migration.
 *
 * @since 1.4.0
 */
class ExternalBusyTimesTableMigration extends AbstractTableMigration {

	/**
	 * Table name.
	 *
	 * @since 1.4.0
	 *
	 * @var string
	 */
	const TABLE_NAME = 'external_busy_times';

	/**
	 * Latest DB schema version.
	 *
	 * @since 1.4.0
	 *
	 * @var int
	 */
	const LATEST_VERSION = 1;

	/**
	 * Create the table.
	 *
	 * @since 1.4.0
	 *
	 * @return WP_Error|true
	 */
	protected function migrate_to_1() {

		global $wpdb;

		$table   = $this->get_table_name();
		$collate = '';

		if ( $wpdb->has_cap( 'collation' ) ) {
			$collate = $wpdb->get_charset_collate();
		}

		$sql = "CREATE TABLE $table (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			employee_id BIGINT UNSIGNED NULL,
			oauth_connection_id BIGINT UNSIGNED NOT NULL,
			provider VARCHAR(50) NOT NULL,
			calendar_id VARCHAR(255) NOT NULL,
			provider_event_id VARCHAR(255) NOT NULL,
			title VARCHAR(255) DEFAULT '',
			start_at DATETIME NOT NULL,
			end_at DATETIME NOT NULL,
			is_all_day TINYINT(1) NOT NULL DEFAULT 0,
			created_at DATETIME NOT NULL,
			updated_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			INDEX idx_employee_time (employee_id, start_at, end_at),
			INDEX idx_connection_time (oauth_connection_id, start_at, end_at),
			UNIQUE KEY uq_provider_event (provider, calendar_id, provider_event_id),
			INDEX idx_provider_event (provider, provider_event_id)
		) {$collate};";

		dbDelta( $sql );

		return ! empty( $wpdb->last_error ) ? new WP_Error( 'migration_failed', $wpdb->last_error ) : true;
	}
}
