-- 抽奖系统数据库初始化脚本
-- 创建系统配置表
CREATE TABLE system_config (
    id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
    admin_password TEXT NOT NULL DEFAULT 'admin123',
    login_password TEXT NOT NULL DEFAULT 'admin123',
    max_draw_times INTEGER DEFAULT 1,
    background_config TEXT DEFAULT '{}',
    hide_positions TEXT DEFAULT '3,4,5,6',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- 创建奖项配置表
CREATE TABLE prize_config (
    id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
    prize_name TEXT NOT NULL,
    prize_level INTEGER NOT NULL CHECK (prize_level IN (1,2,3,4)),
    total_quantity INTEGER NOT NULL DEFAULT 0,
    remaining_quantity INTEGER NOT NULL DEFAULT 0,
    probability REAL DEFAULT 0.0000,
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- 创建学生表
CREATE TABLE students (
    student_id TEXT PRIMARY KEY,
    draw_count INTEGER DEFAULT 0,
    first_draw_at DATETIME,
    last_draw_at DATETIME
);

-- 创建抽奖记录表
CREATE TABLE lottery_records (
    id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
    student_id TEXT NOT NULL,
    prize_id TEXT REFERENCES prize_config(id),
    prize_name TEXT NOT NULL,
    prize_level INTEGER NOT NULL,
    draw_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_synced INTEGER DEFAULT 0,
    cache_data TEXT DEFAULT '{}'
);

-- 创建索引
CREATE INDEX idx_lottery_records_student_id ON lottery_records(student_id);
CREATE INDEX idx_lottery_records_draw_time ON lottery_records(draw_time DESC);
CREATE INDEX idx_lottery_records_prize_level ON lottery_records(prize_level);
CREATE INDEX idx_students_draw_count ON students(draw_count);

-- 创建触发器用于更新时间戳
CREATE TRIGGER update_system_config_timestamp 
    AFTER UPDATE ON system_config
    BEGIN
        UPDATE system_config SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.id;
    END;

-- 初始化数据
INSERT INTO system_config (admin_password, login_password, max_draw_times) VALUES ('admin123', 'admin123', 1);

INSERT INTO prize_config (prize_name, prize_level, total_quantity, remaining_quantity, probability) VALUES
('一等奖-iPad', 1, 1, 1, 0.0010),
('二等奖-蓝牙耳机', 2, 5, 5, 0.0050),
('三等奖-保温杯', 3, 20, 20, 0.0200),
('谢谢参与', 4, 9974, 9974, 0.9740);