-- migrations/000001_init_schema.up.sql
-- 初始化数据库 Schema
-- 创建 tb_user 和 tb_order 表、索引
-- 注意: 表关系和 updated_at 更新在代码中处理

-- 用户表
CREATE TABLE IF NOT EXISTS tb_user (
    id SERIAL PRIMARY KEY,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP,
    
    -- 基本信息
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    password VARCHAR(255) NOT NULL,
    
    -- 状态字段
    status VARCHAR(20) NOT NULL DEFAULT 'active',
    
    -- 元数据
    last_login_at TIMESTAMP,
    
    -- 唯一约束
    CONSTRAINT uk_user_username UNIQUE (username),
    CONSTRAINT uk_user_email UNIQUE (email)
);

-- 用户表索引
CREATE INDEX idx_user_deleted_at ON tb_user(deleted_at);
CREATE INDEX idx_user_status ON tb_user(status);
CREATE INDEX idx_user_created_at ON tb_user(created_at);

-- 订单表
CREATE TABLE IF NOT EXISTS tb_order (
    id SERIAL PRIMARY KEY,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP,
    
    -- 业务唯一键
    order_id VARCHAR(50) NOT NULL,
    
    -- 关联关系 (注意: 无数据库外键约束，在代码中管理)
    user_id INTEGER NOT NULL,
    
    -- 订单信息
    amount BIGINT NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    remark VARCHAR(500),
    
    -- 时间字段
    paid_at TIMESTAMP,
    completed_at TIMESTAMP,
    
    -- 唯一约束
    CONSTRAINT uk_order_order_id UNIQUE (order_id)
);

-- 订单表索引
CREATE INDEX idx_order_deleted_at ON tb_order(deleted_at);
CREATE INDEX idx_order_user_id ON tb_order(user_id);
CREATE INDEX idx_order_status ON tb_order(status);
CREATE INDEX idx_order_created_at ON tb_order(created_at);
CREATE INDEX idx_order_order_id ON tb_order(order_id);

-- 添加注释
COMMENT ON TABLE tb_user IS '用户表';
COMMENT ON COLUMN tb_user.username IS '用户名（唯一）';
COMMENT ON COLUMN tb_user.email IS '邮箱（唯一）';
COMMENT ON COLUMN tb_user.password IS '密码（bcrypt 哈希）';
COMMENT ON COLUMN tb_user.status IS '用户状态：active, inactive, suspended';
COMMENT ON COLUMN tb_user.deleted_at IS '软删除时间';

COMMENT ON TABLE tb_order IS '订单表';
COMMENT ON COLUMN tb_order.order_id IS '订单号（业务唯一键）';
COMMENT ON COLUMN tb_order.user_id IS '用户 ID（在代码中维护关联，无数据库外键）';
COMMENT ON COLUMN tb_order.amount IS '金额（分）';
COMMENT ON COLUMN tb_order.status IS '订单状态：pending, paid, processing, completed, cancelled';
COMMENT ON COLUMN tb_order.deleted_at IS '软删除时间';
