-- CreateEnum
CREATE TYPE "AuditActionType" AS ENUM (
    'SELL_ORDER_CREATED',
    'SELL_ORDER_EXECUTED',
    'TRADE_PASSWORD_SET',
    'TRADE_PASSWORD_CHANGED',
    'TRADE_PASSWORD_VERIFIED',
    'TRADE_PASSWORD_FAILED',
    'TRANSFER_IN',
    'TRANSFER_OUT',
    'P2P_TRANSFER'
);

-- CreateTable
-- 审计分类账（Append-Only）
-- 设计原则：只增加，不修改，不删除
-- 用于记录所有敏感操作，如交易、支付密码验证等
CREATE TABLE "audit_ledgers" (
    "id" TEXT NOT NULL,
    "account_sequence" TEXT NOT NULL,
    "action_type" "AuditActionType" NOT NULL,
    "action_detail" JSONB NOT NULL,
    "ip_address" VARCHAR(45),
    "user_agent" TEXT,
    "prev_hash" VARCHAR(64),
    "record_hash" VARCHAR(64) NOT NULL,
    "reference_id" TEXT,
    "reference_type" TEXT,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateIndex
-- 按用户和时间查询
CREATE INDEX "audit_ledgers_account_sequence_created_at_idx" ON "audit_ledgers"("account_sequence", "created_at" DESC);

-- CreateIndex
-- 按操作类型查询
CREATE INDEX "audit_ledgers_action_type_idx" ON "audit_ledgers"("action_type");

-- CreateIndex
-- 按关联业务ID查询
CREATE INDEX "audit_ledgers_reference_id_idx" ON "audit_ledgers"("reference_id");

-- CreateIndex
-- 按时间查询
CREATE INDEX "audit_ledgers_created_at_idx" ON "audit_ledgers"("created_at" DESC);

-- 添加注释说明该表为Append-Only设计
COMMENT ON TABLE "audit_ledgers" IS '审计分类账 - Append-Only设计，仅支持INSERT操作，禁止UPDATE和DELETE';
