-- ============================================================================
-- trading-service 初始化 migration
-- 合并自: 0001_init, 0002_add_trading_burn_system, 0003_add_processed_events,
--         0004_add_buy_enabled, 0005_add_market_maker_and_order_source,
--         0006_add_market_maker_depth, 0007_add_trade_fee, 0008_add_c2c_orders,
--         0009_add_original_quantity
-- ============================================================================

-- CreateEnum
CREATE TYPE "OutboxStatus" AS ENUM ('PENDING', 'PUBLISHED', 'FAILED');

-- CreateTable
CREATE TABLE "trading_accounts" (
    "id" TEXT NOT NULL,
    "accountSequence" TEXT NOT NULL,
    "shareBalance" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "cashBalance" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "frozenShares" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "frozenCash" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "totalBought" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "totalSold" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "trading_accounts_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "orders" (
    "id" TEXT NOT NULL,
    "orderNo" TEXT NOT NULL,
    "accountSequence" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "status" TEXT NOT NULL,
    "price" DECIMAL(30,18) NOT NULL,
    "quantity" DECIMAL(30,8) NOT NULL,
    "filledQuantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "remainingQuantity" DECIMAL(30,8) NOT NULL,
    "averagePrice" DECIMAL(30,18) NOT NULL DEFAULT 0,
    "totalAmount" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "burn_quantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "burn_multiplier" DECIMAL(30,18) NOT NULL DEFAULT 0,
    "effective_quantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "source" TEXT NOT NULL DEFAULT 'USER',
    "source_label" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    "cancelledAt" TIMESTAMP(3),
    "completedAt" TIMESTAMP(3),

    CONSTRAINT "orders_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "trades" (
    "id" TEXT NOT NULL,
    "tradeNo" TEXT NOT NULL,
    "buy_order_id" TEXT NOT NULL,
    "sell_order_id" TEXT NOT NULL,
    "buyer_sequence" TEXT NOT NULL,
    "seller_sequence" TEXT NOT NULL,
    "price" DECIMAL(30,18) NOT NULL,
    "quantity" DECIMAL(30,8) NOT NULL,
    "original_quantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "amount" DECIMAL(30,8) NOT NULL,
    "burn_quantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "effective_qty" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "fee" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "buyer_source" TEXT NOT NULL DEFAULT 'USER',
    "seller_source" TEXT NOT NULL DEFAULT 'USER',
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "trades_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "trading_transactions" (
    "id" TEXT NOT NULL,
    "accountSequence" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "assetType" TEXT NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "balanceBefore" DECIMAL(30,8) NOT NULL,
    "balanceAfter" DECIMAL(30,8) NOT NULL,
    "referenceId" TEXT,
    "referenceType" TEXT,
    "counterparty_type" TEXT,
    "counterparty_account_seq" TEXT,
    "counterparty_user_id" TEXT,
    "memo" TEXT,
    "description" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "trading_transactions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "circulation_pools" (
    "id" TEXT NOT NULL,
    "totalShares" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "totalCash" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "totalInflow" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "totalOutflow" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "circulation_pools_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "circulation_pool_transactions" (
    "id" TEXT NOT NULL,
    "pool_id" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "assetType" TEXT NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "balance_before" DECIMAL(30,8) NOT NULL,
    "balance_after" DECIMAL(30,8) NOT NULL,
    "counterparty_type" TEXT,
    "counterparty_account_seq" TEXT,
    "counterparty_user_id" TEXT,
    "reference_id" TEXT,
    "reference_type" TEXT,
    "memo" TEXT,
    "metadata" JSONB,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "circulation_pool_transactions_pkey" PRIMARY KEY ("id")
);

-- CreateTable (deprecated, kept for compatibility)
CREATE TABLE "pool_transactions" (
    "id" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "referenceId" TEXT,
    "description" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "pool_transactions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "minute_klines" (
    "id" TEXT NOT NULL,
    "minute" TIMESTAMP(3) NOT NULL,
    "open" DECIMAL(30,18) NOT NULL,
    "high" DECIMAL(30,18) NOT NULL,
    "low" DECIMAL(30,18) NOT NULL,
    "close" DECIMAL(30,18) NOT NULL,
    "volume" DECIMAL(30,8) NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "tradeCount" INTEGER NOT NULL DEFAULT 0,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "minute_klines_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "hour_klines" (
    "id" TEXT NOT NULL,
    "hour" TIMESTAMP(3) NOT NULL,
    "open" DECIMAL(30,18) NOT NULL,
    "high" DECIMAL(30,18) NOT NULL,
    "low" DECIMAL(30,18) NOT NULL,
    "close" DECIMAL(30,18) NOT NULL,
    "volume" DECIMAL(30,8) NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "tradeCount" INTEGER NOT NULL DEFAULT 0,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "hour_klines_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "day_klines" (
    "id" TEXT NOT NULL,
    "date" DATE NOT NULL,
    "open" DECIMAL(30,18) NOT NULL,
    "high" DECIMAL(30,18) NOT NULL,
    "low" DECIMAL(30,18) NOT NULL,
    "close" DECIMAL(30,18) NOT NULL,
    "volume" DECIMAL(30,8) NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "tradeCount" INTEGER NOT NULL DEFAULT 0,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "day_klines_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "transfer_records" (
    "id" TEXT NOT NULL,
    "transferNo" TEXT NOT NULL,
    "accountSequence" TEXT NOT NULL,
    "direction" TEXT NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "status" TEXT NOT NULL,
    "miningTxId" TEXT,
    "errorMessage" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "completedAt" TIMESTAMP(3),

    CONSTRAINT "transfer_records_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "outbox_events" (
    "id" TEXT NOT NULL,
    "aggregate_type" TEXT NOT NULL,
    "aggregate_id" TEXT NOT NULL,
    "event_type" TEXT NOT NULL,
    "payload" JSONB NOT NULL,
    "topic" TEXT NOT NULL DEFAULT 'trading.events',
    "key" TEXT,
    "status" "OutboxStatus" NOT NULL DEFAULT 'PENDING',
    "retry_count" INTEGER NOT NULL DEFAULT 0,
    "max_retries" INTEGER NOT NULL DEFAULT 10,
    "last_error" TEXT,
    "published_at" TIMESTAMP(3),
    "next_retry_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "outbox_events_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "trading_accounts_accountSequence_key" ON "trading_accounts"("accountSequence");

-- CreateIndex
CREATE UNIQUE INDEX "orders_orderNo_key" ON "orders"("orderNo");

-- CreateIndex
CREATE INDEX "orders_accountSequence_status_idx" ON "orders"("accountSequence", "status");

-- CreateIndex
CREATE INDEX "orders_type_status_price_idx" ON "orders"("type", "status", "price");

-- CreateIndex
CREATE INDEX "orders_createdAt_idx" ON "orders"("createdAt" DESC);

-- CreateIndex
CREATE INDEX "orders_source_idx" ON "orders"("source");

-- CreateIndex
CREATE UNIQUE INDEX "trades_tradeNo_key" ON "trades"("tradeNo");

-- CreateIndex
CREATE INDEX "trades_buyer_sequence_idx" ON "trades"("buyer_sequence");

-- CreateIndex
CREATE INDEX "trades_seller_sequence_idx" ON "trades"("seller_sequence");

-- CreateIndex
CREATE INDEX "trades_created_at_idx" ON "trades"("created_at" DESC);

-- CreateIndex
CREATE INDEX "trades_buyer_source_idx" ON "trades"("buyer_source");

-- CreateIndex
CREATE INDEX "trades_seller_source_idx" ON "trades"("seller_source");

-- CreateIndex
CREATE INDEX "trading_transactions_accountSequence_createdAt_idx" ON "trading_transactions"("accountSequence", "createdAt" DESC);

-- CreateIndex
CREATE INDEX "trading_transactions_counterparty_account_seq_idx" ON "trading_transactions"("counterparty_account_seq");

-- CreateIndex
CREATE INDEX "trading_transactions_counterparty_user_id_idx" ON "trading_transactions"("counterparty_user_id");

-- CreateIndex
CREATE INDEX "circulation_pool_transactions_pool_id_created_at_idx" ON "circulation_pool_transactions"("pool_id", "created_at" DESC);

-- CreateIndex
CREATE INDEX "circulation_pool_transactions_type_assetType_idx" ON "circulation_pool_transactions"("type", "assetType");

-- CreateIndex
CREATE INDEX "circulation_pool_transactions_counterparty_account_seq_idx" ON "circulation_pool_transactions"("counterparty_account_seq");

-- CreateIndex
CREATE INDEX "circulation_pool_transactions_counterparty_user_id_idx" ON "circulation_pool_transactions"("counterparty_user_id");

-- CreateIndex
CREATE INDEX "circulation_pool_transactions_reference_id_idx" ON "circulation_pool_transactions"("reference_id");

-- CreateIndex
CREATE INDEX "circulation_pool_transactions_created_at_idx" ON "circulation_pool_transactions"("created_at" DESC);

-- CreateIndex
CREATE INDEX "pool_transactions_createdAt_idx" ON "pool_transactions"("createdAt" DESC);

-- CreateIndex
CREATE UNIQUE INDEX "minute_klines_minute_key" ON "minute_klines"("minute");

-- CreateIndex
CREATE INDEX "minute_klines_minute_idx" ON "minute_klines"("minute" DESC);

-- CreateIndex
CREATE UNIQUE INDEX "hour_klines_hour_key" ON "hour_klines"("hour");

-- CreateIndex
CREATE INDEX "hour_klines_hour_idx" ON "hour_klines"("hour" DESC);

-- CreateIndex
CREATE UNIQUE INDEX "day_klines_date_key" ON "day_klines"("date");

-- CreateIndex
CREATE INDEX "day_klines_date_idx" ON "day_klines"("date" DESC);

-- CreateIndex
CREATE UNIQUE INDEX "transfer_records_transferNo_key" ON "transfer_records"("transferNo");

-- CreateIndex
CREATE INDEX "transfer_records_accountSequence_idx" ON "transfer_records"("accountSequence");

-- CreateIndex
CREATE INDEX "transfer_records_status_idx" ON "transfer_records"("status");

-- CreateIndex
CREATE INDEX "outbox_events_status_idx" ON "outbox_events"("status");

-- CreateIndex
CREATE INDEX "outbox_events_next_retry_at_idx" ON "outbox_events"("next_retry_at");

-- CreateIndex
CREATE INDEX "outbox_events_created_at_idx" ON "outbox_events"("created_at");

-- AddForeignKey
ALTER TABLE "orders" ADD CONSTRAINT "orders_accountSequence_fkey" FOREIGN KEY ("accountSequence") REFERENCES "trading_accounts"("accountSequence") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "trades" ADD CONSTRAINT "trades_buy_order_id_fkey" FOREIGN KEY ("buy_order_id") REFERENCES "orders"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "trading_transactions" ADD CONSTRAINT "trading_transactions_accountSequence_fkey" FOREIGN KEY ("accountSequence") REFERENCES "trading_accounts"("accountSequence") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "circulation_pool_transactions" ADD CONSTRAINT "circulation_pool_transactions_pool_id_fkey" FOREIGN KEY ("pool_id") REFERENCES "circulation_pools"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- ============================================================================
-- 交易配置和销毁系统 (从 0002_add_trading_burn_system 合并)
-- ============================================================================

-- CreateTable
CREATE TABLE "trading_configs" (
    "id" TEXT NOT NULL,
    "total_shares" DECIMAL(30,8) NOT NULL DEFAULT 10002000000,
    "burn_target" DECIMAL(30,8) NOT NULL DEFAULT 10000000000,
    "burn_period_minutes" INTEGER NOT NULL DEFAULT 2102400,
    "minute_burn_rate" DECIMAL(30,18) NOT NULL DEFAULT 4756.468797564687,
    "is_active" BOOLEAN NOT NULL DEFAULT false,
    "buy_enabled" BOOLEAN NOT NULL DEFAULT false,
    "depth_enabled" BOOLEAN NOT NULL DEFAULT false,
    "activated_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "trading_configs_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "black_holes" (
    "id" TEXT NOT NULL,
    "total_burned" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "target_burn" DECIMAL(30,8) NOT NULL,
    "remaining_burn" DECIMAL(30,8) NOT NULL,
    "last_burn_minute" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "black_holes_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "burn_records" (
    "id" TEXT NOT NULL,
    "black_hole_id" TEXT NOT NULL,
    "burn_minute" TIMESTAMP(3) NOT NULL,
    "burn_amount" DECIMAL(30,18) NOT NULL,
    "remaining_target" DECIMAL(30,8) NOT NULL,
    "source_type" TEXT,
    "source_account_seq" TEXT,
    "source_order_no" TEXT,
    "memo" TEXT,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "burn_records_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "burn_records_burn_minute_idx" ON "burn_records"("burn_minute");
CREATE INDEX "burn_records_source_account_seq_idx" ON "burn_records"("source_account_seq");
CREATE INDEX "burn_records_source_order_no_idx" ON "burn_records"("source_order_no");
CREATE INDEX "burn_records_source_type_idx" ON "burn_records"("source_type");

-- AddForeignKey
ALTER TABLE "burn_records" ADD CONSTRAINT "burn_records_black_hole_id_fkey" FOREIGN KEY ("black_hole_id") REFERENCES "black_holes"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- CreateTable
CREATE TABLE "share_pools" (
    "id" TEXT NOT NULL,
    "green_points" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "total_inflow" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "total_outflow" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "share_pools_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "share_pool_transactions" (
    "id" TEXT NOT NULL,
    "pool_id" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "balance_before" DECIMAL(30,8) NOT NULL,
    "balance_after" DECIMAL(30,8) NOT NULL,
    "reference_id" TEXT,
    "reference_type" TEXT,
    "memo" TEXT,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "share_pool_transactions_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "share_pool_transactions_pool_id_created_at_idx" ON "share_pool_transactions"("pool_id", "created_at" DESC);

-- AddForeignKey
ALTER TABLE "share_pool_transactions" ADD CONSTRAINT "share_pool_transactions_pool_id_fkey" FOREIGN KEY ("pool_id") REFERENCES "share_pools"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- CreateTable
CREATE TABLE "price_snapshots" (
    "id" TEXT NOT NULL,
    "snapshot_time" TIMESTAMP(3) NOT NULL,
    "price" DECIMAL(30,18) NOT NULL,
    "green_points" DECIMAL(30,8) NOT NULL,
    "black_hole_amount" DECIMAL(30,8) NOT NULL,
    "circulation_pool" DECIMAL(30,8) NOT NULL,
    "effective_denominator" DECIMAL(30,8) NOT NULL,
    "minute_burn_rate" DECIMAL(30,18) NOT NULL,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "price_snapshots_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "price_snapshots_snapshot_time_key" ON "price_snapshots"("snapshot_time");
CREATE INDEX "price_snapshots_snapshot_time_idx" ON "price_snapshots"("snapshot_time" DESC);

-- ============================================================================
-- 事件幂等处理 (从 0003_add_processed_events 合并)
-- ============================================================================

-- CreateTable
CREATE TABLE "processed_events" (
    "id" TEXT NOT NULL,
    "event_id" TEXT NOT NULL,
    "event_type" TEXT NOT NULL,
    "source_service" TEXT NOT NULL,
    "processed_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "processed_events_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "processed_events_event_id_key" ON "processed_events"("event_id");
CREATE INDEX "processed_events_event_id_idx" ON "processed_events"("event_id");
CREATE INDEX "processed_events_processed_at_idx" ON "processed_events"("processed_at");

-- ============================================================================
-- 做市商系统 (从 0005_add_market_maker_and_order_source 合并)
-- ============================================================================

-- CreateTable
CREATE TABLE "market_maker_configs" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "account_sequence" TEXT NOT NULL,
    "cash_balance" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "share_balance" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "frozen_cash" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "frozen_shares" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "max_buy_ratio" DECIMAL(10,4) NOT NULL DEFAULT 0.05,
    "min_interval_ms" INTEGER NOT NULL DEFAULT 1000,
    "max_interval_ms" INTEGER NOT NULL DEFAULT 4000,
    "price_strategy" TEXT NOT NULL DEFAULT 'TAKER',
    "discount_rate" DECIMAL(10,4) NOT NULL DEFAULT 1.0,
    "is_active" BOOLEAN NOT NULL DEFAULT false,
    "last_run_at" TIMESTAMP(3),
    "total_buy_count" INTEGER NOT NULL DEFAULT 0,
    "total_buy_quantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "total_buy_amount" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "total_sell_count" INTEGER NOT NULL DEFAULT 0,
    "total_sell_quantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "total_sell_amount" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "maker_enabled" BOOLEAN NOT NULL DEFAULT false,
    "bid_enabled" BOOLEAN NOT NULL DEFAULT true,
    "bid_levels" INTEGER NOT NULL DEFAULT 5,
    "bid_spread" DECIMAL(10,4) NOT NULL DEFAULT 0.01,
    "bid_level_spacing" DECIMAL(10,4) NOT NULL DEFAULT 0.005,
    "bid_quantity_per_level" DECIMAL(30,8) NOT NULL DEFAULT 1000,
    "ask_enabled" BOOLEAN NOT NULL DEFAULT true,
    "ask_levels" INTEGER NOT NULL DEFAULT 5,
    "ask_spread" DECIMAL(10,4) NOT NULL DEFAULT 0.01,
    "ask_level_spacing" DECIMAL(10,4) NOT NULL DEFAULT 0.005,
    "ask_quantity_per_level" DECIMAL(30,8) NOT NULL DEFAULT 1000,
    "refresh_interval_ms" INTEGER NOT NULL DEFAULT 60000,
    "last_refresh_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "market_maker_configs_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "market_maker_configs_name_key" ON "market_maker_configs"("name");
CREATE UNIQUE INDEX "market_maker_configs_account_sequence_key" ON "market_maker_configs"("account_sequence");

-- CreateTable
CREATE TABLE "market_maker_ledgers" (
    "id" TEXT NOT NULL,
    "market_maker_id" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "asset_type" TEXT NOT NULL,
    "amount" DECIMAL(30,8) NOT NULL,
    "balance_before" DECIMAL(30,8) NOT NULL,
    "balance_after" DECIMAL(30,8) NOT NULL,
    "trade_id" TEXT,
    "trade_no" TEXT,
    "order_id" TEXT,
    "order_no" TEXT,
    "counterparty_seq" TEXT,
    "counterparty_id" TEXT,
    "price" DECIMAL(30,18),
    "quantity" DECIMAL(30,8),
    "memo" TEXT,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "market_maker_ledgers_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "market_maker_ledgers_market_maker_id_created_at_idx" ON "market_maker_ledgers"("market_maker_id", "created_at" DESC);
CREATE INDEX "market_maker_ledgers_type_idx" ON "market_maker_ledgers"("type");
CREATE INDEX "market_maker_ledgers_trade_no_idx" ON "market_maker_ledgers"("trade_no");
CREATE INDEX "market_maker_ledgers_order_no_idx" ON "market_maker_ledgers"("order_no");
CREATE INDEX "market_maker_ledgers_counterparty_seq_idx" ON "market_maker_ledgers"("counterparty_seq");
CREATE INDEX "market_maker_ledgers_created_at_idx" ON "market_maker_ledgers"("created_at" DESC);

-- AddForeignKey
ALTER TABLE "market_maker_ledgers" ADD CONSTRAINT "market_maker_ledgers_market_maker_id_fkey" FOREIGN KEY ("market_maker_id") REFERENCES "market_maker_configs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- CreateTable
CREATE TABLE "market_maker_daily_stats" (
    "id" TEXT NOT NULL,
    "market_maker_id" TEXT NOT NULL,
    "date" DATE NOT NULL,
    "buy_count" INTEGER NOT NULL DEFAULT 0,
    "buy_quantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "buy_amount" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "avg_buy_price" DECIMAL(30,18) NOT NULL DEFAULT 0,
    "sell_count" INTEGER NOT NULL DEFAULT 0,
    "sell_quantity" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "sell_amount" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "avg_sell_price" DECIMAL(30,18) NOT NULL DEFAULT 0,
    "realized_pnl" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "cash_balance_end" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "share_balance_end" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "market_maker_daily_stats_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "market_maker_daily_stats_market_maker_id_date_key" ON "market_maker_daily_stats"("market_maker_id", "date");
CREATE INDEX "market_maker_daily_stats_market_maker_id_date_idx" ON "market_maker_daily_stats"("market_maker_id", "date" DESC);

-- CreateTable
CREATE TABLE "market_maker_orders" (
    "id" TEXT NOT NULL,
    "market_maker_id" TEXT NOT NULL,
    "order_id" TEXT NOT NULL,
    "order_no" TEXT NOT NULL,
    "side" TEXT NOT NULL,
    "level" INTEGER NOT NULL,
    "price" DECIMAL(30,18) NOT NULL,
    "quantity" DECIMAL(30,8) NOT NULL,
    "remaining_qty" DECIMAL(30,8) NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'ACTIVE',
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "market_maker_orders_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "market_maker_orders_order_id_key" ON "market_maker_orders"("order_id");
CREATE UNIQUE INDEX "market_maker_orders_order_no_key" ON "market_maker_orders"("order_no");
CREATE INDEX "market_maker_orders_market_maker_id_side_status_idx" ON "market_maker_orders"("market_maker_id", "side", "status");
CREATE INDEX "market_maker_orders_status_idx" ON "market_maker_orders"("status");

-- AddForeignKey
ALTER TABLE "market_maker_orders" ADD CONSTRAINT "market_maker_orders_market_maker_id_fkey" FOREIGN KEY ("market_maker_id") REFERENCES "market_maker_configs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- ============================================================================
-- C2C 交易系统 (从 0008_add_c2c_orders 合并)
-- ============================================================================

-- CreateEnum
CREATE TYPE "C2cOrderType" AS ENUM ('BUY', 'SELL');

-- CreateEnum
CREATE TYPE "C2cOrderStatus" AS ENUM ('PENDING', 'MATCHED', 'PAID', 'COMPLETED', 'CANCELLED', 'EXPIRED');

-- CreateEnum
CREATE TYPE "C2cPaymentMethod" AS ENUM ('ALIPAY', 'WECHAT', 'BANK');

-- CreateTable
CREATE TABLE "c2c_orders" (
    "id" TEXT NOT NULL,
    "order_no" TEXT NOT NULL,
    "type" "C2cOrderType" NOT NULL,
    "status" "C2cOrderStatus" NOT NULL DEFAULT 'PENDING',
    "maker_account_sequence" TEXT NOT NULL,
    "maker_user_id" TEXT,
    "maker_phone" TEXT,
    "maker_nickname" TEXT,
    "taker_account_sequence" TEXT,
    "taker_user_id" TEXT,
    "taker_phone" TEXT,
    "taker_nickname" TEXT,
    "price" DECIMAL(30,18) NOT NULL,
    "quantity" DECIMAL(30,8) NOT NULL,
    "total_amount" DECIMAL(30,8) NOT NULL,
    "min_amount" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "max_amount" DECIMAL(30,8) NOT NULL DEFAULT 0,
    "payment_method" "C2cPaymentMethod",
    "payment_account" TEXT,
    "payment_qr_code" TEXT,
    "payment_real_name" TEXT,
    "remark" TEXT,
    "payment_timeout_minutes" INTEGER NOT NULL DEFAULT 15,
    "confirm_timeout_minutes" INTEGER NOT NULL DEFAULT 60,
    "payment_deadline" TIMESTAMP(3),
    "confirm_deadline" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,
    "matched_at" TIMESTAMP(3),
    "paid_at" TIMESTAMP(3),
    "completed_at" TIMESTAMP(3),
    "cancelled_at" TIMESTAMP(3),
    "expired_at" TIMESTAMP(3),

    CONSTRAINT "c2c_orders_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "c2c_orders_order_no_key" ON "c2c_orders"("order_no");
CREATE INDEX "c2c_orders_status_idx" ON "c2c_orders"("status");
CREATE INDEX "c2c_orders_type_status_idx" ON "c2c_orders"("type", "status");
CREATE INDEX "c2c_orders_maker_account_sequence_idx" ON "c2c_orders"("maker_account_sequence");
CREATE INDEX "c2c_orders_taker_account_sequence_idx" ON "c2c_orders"("taker_account_sequence");
CREATE INDEX "c2c_orders_created_at_idx" ON "c2c_orders"("created_at" DESC);
CREATE INDEX "c2c_orders_payment_deadline_idx" ON "c2c_orders"("payment_deadline");
CREATE INDEX "c2c_orders_confirm_deadline_idx" ON "c2c_orders"("confirm_deadline");
