-- 股票投资分析系统 - PostgreSQL 数据库初始化脚本
-- 运行方式: psql -U postgres -f init_db.sql

-- 创建数据库（如果不存在）
SELECT 'CREATE DATABASE stock_app' 
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'stock_app')\gexec

-- 连接到数据库
\c stock_app

-- 用户表
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    available_cash DECIMAL(15,2) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 关注列表
CREATE TABLE IF NOT EXISTS watchlist (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    stock_code VARCHAR(10) NOT NULL,
    stock_name VARCHAR(50),
    added_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(user_id, stock_code)
);

-- 交易记录
CREATE TABLE IF NOT EXISTS trades (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    stock_code VARCHAR(10) NOT NULL,
    stock_name VARCHAR(50),
    trade_type VARCHAR(10) NOT NULL,
    price DECIMAL(10,4),
    quantity INTEGER,
    trade_date DATE,
    reason TEXT,
    result VARCHAR(20),
    profit_amount DECIMAL(10,4),
    stop_loss_price DECIMAL(10,4),
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 分析缓存
CREATE TABLE IF NOT EXISTS alerts_cache (
    id SERIAL PRIMARY KEY,
    user_id INTEGER UNIQUE REFERENCES users(id) ON DELETE CASCADE,
    data JSONB,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 股票名称缓存（公共）
CREATE TABLE IF NOT EXISTS stock_names (
    code VARCHAR(10) PRIMARY KEY,
    name VARCHAR(50)
);

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_watchlist_user ON watchlist(user_id);
CREATE INDEX IF NOT EXISTS idx_trades_user ON trades(user_id);
CREATE INDEX IF NOT EXISTS idx_trades_stock ON trades(stock_code);
CREATE INDEX IF NOT EXISTS idx_alerts_user ON alerts_cache(user_id);

-- 输出结果
SELECT 'Database initialized successfully!' as status;
