CREATE DATABASE IF NOT EXISTS hy_wallet DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hy_wallet;

CREATE TABLE IF NOT EXISTS wallet_accounts (
  user_id BIGINT NOT NULL,
  currency VARCHAR(32) NOT NULL,
  balance BIGINT NOT NULL,
  version BIGINT NOT NULL,
  created_at_ms BIGINT NOT NULL,
  updated_at_ms BIGINT NOT NULL,
  PRIMARY KEY (user_id, currency)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS wallet_ledger (
  ledger_id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  billing_receipt_id VARCHAR(96) NOT NULL,
  command_id VARCHAR(96) NOT NULL,
  user_id BIGINT NOT NULL,
  room_id VARCHAR(96) NOT NULL,
  counterparty_user_id BIGINT NOT NULL,
  currency VARCHAR(32) NOT NULL,
  amount BIGINT NOT NULL,
  direction VARCHAR(16) NOT NULL,
  balance_after BIGINT NOT NULL,
  biz_type VARCHAR(64) NOT NULL,
  created_at_ms BIGINT NOT NULL,
  UNIQUE KEY uk_wallet_ledger_receipt (billing_receipt_id),
  UNIQUE KEY uk_wallet_ledger_command_user (command_id, user_id),
  KEY idx_wallet_ledger_user_time (user_id, created_at_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS wallet_idempotency (
  command_id VARCHAR(96) NOT NULL PRIMARY KEY,
  billing_receipt_id VARCHAR(96) NOT NULL,
  request_hash VARCHAR(128) NOT NULL,
  expires_at_ms BIGINT NOT NULL,
  created_at_ms BIGINT NOT NULL,
  KEY idx_wallet_idempotency_expires_at (expires_at_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
