<?php

declare(strict_types=1);

if (! defined('ABSPATH')) {
	exit;
}

final class CRToday_Storage_Installer {
	private const OPTION_DB_VERSION = 'crtoday_storage_schema_version';
	private const DB_VERSION = '1.0.0';

	public static function maybe_install(): void {
		$current = (string) get_option(self::OPTION_DB_VERSION, '');
		if ($current === self::DB_VERSION) {
			return;
		}

		self::install_or_upgrade();
		update_option(self::OPTION_DB_VERSION, self::DB_VERSION, false);
	}

	public static function drop_tables(): void {
		global $wpdb;

		$rates = self::rates_table();
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange -- Explicit uninstall cleanup.
		$wpdb->query($wpdb->prepare('DROP TABLE IF EXISTS %i', $rates));

		delete_option(self::OPTION_DB_VERSION);
	}

	/**
	 * Truncate (empty) the rates table without dropping it.
	 * @return int Number of rows deleted.
	 */
	public static function truncate_rates_table(): int {
		global $wpdb;

		$rates = self::rates_table();
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Truncate operation is explicit user/admin action.
		$rows = (int) $wpdb->query($wpdb->prepare('DELETE FROM %i', $rates));

		return $rows;
	}

	public static function rates_table(): string {
		global $wpdb;
		return $wpdb->prefix . 'crtoday_rates';
	}

	/**
	 * Check whether a database table exists.
	 *
	 * @param string $table Fully-qualified table name including prefix.
	 */
	public static function table_exists(string $table): bool {
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Lightweight schema existence check.
		$found = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table));
		return is_string($found) && $found === $table;
	}

	private static function install_or_upgrade(): void {
		global $wpdb;

		$rates = self::rates_table();
		$charset_collate = $wpdb->get_charset_collate();

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

		$rates_sql = "
		CREATE TABLE {$rates} (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			source varchar(32) NOT NULL,
			deal varchar(32) NOT NULL DEFAULT 'STANDARD',
			base varchar(8) NOT NULL,
			code varchar(8) NOT NULL,
			interval_min smallint(5) unsigned NOT NULL,
			rate_day_utc date NOT NULL,
			source_ts_utc datetime NOT NULL,
			fetch_ts_utc datetime NOT NULL,
			bid decimal(20,10) NULL,
			ask decimal(20,10) NULL,
			mid decimal(20,10) NULL,
			snapshot_hash char(64) NOT NULL,
			created_at_utc datetime NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY uq_rates_value (source,deal,base,code,interval_min,rate_day_utc,snapshot_hash),
			KEY idx_rates_latest (source,deal,interval_min,code,source_ts_utc),
			KEY idx_rates_day (source,deal,interval_min,rate_day_utc,source_ts_utc),
			KEY idx_rates_purge (rate_day_utc,source_ts_utc)
		) {$charset_collate};
		";

		dbDelta($rates_sql);
	}
}
