<?php
/**
 * Migration: Create the price history table.
 *
 * One row per detected price change on a listing.  `delta` is the signed
 * change ( new - old ) so simple "price went DOWN" filters can be done in
 * SQL: `WHERE delta < 0`.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Database\Migrations;

use ThemeREX\AutoDealer\Database\MigrationInterface;

class CreatePriceHistoryTable implements MigrationInterface {

	public function up( \wpdb $wpdb ): void {
		$table          = $wpdb->prefix . 'trx_ad_price_history';
		$charsetCollate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE {$table} (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			post_id bigint(20) unsigned NOT NULL,
			old_price decimal(12,2) DEFAULT NULL,
			new_price decimal(12,2) DEFAULT NULL,
			delta decimal(12,2) NOT NULL DEFAULT 0.00,
			currency varchar(6) NOT NULL DEFAULT 'USD',
			source varchar(32) NOT NULL DEFAULT 'edit',
			changed_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY post_id (post_id),
			KEY changed_at (changed_at),
			KEY post_changed (post_id, changed_at),
			KEY delta_index (delta)
		) {$charsetCollate};";

		dbDelta( $sql );
	}

	public function getVersion(): int {
		return 2;
	}
}
