-- Weibo-HotSign Database Initialization Script for MySQL
-- 创建表结构（数据库需提前创建好）
-- 如需手动建库: CREATE DATABASE weibo_hotsign DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Users table
CREATE TABLE IF NOT EXISTS users (
    id CHAR(36) PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE,
    hashed_password VARCHAR(255),
    wx_openid VARCHAR(64) UNIQUE,
    wx_nickname VARCHAR(100),
    wx_avatar VARCHAR(500),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT TRUE,
    INDEX idx_users_email (email),
    INDEX idx_users_username (username),
    INDEX idx_users_wx_openid (wx_openid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Accounts table
CREATE TABLE IF NOT EXISTS accounts (
    id CHAR(36) PRIMARY KEY,
    user_id CHAR(36) NOT NULL,
    weibo_user_id VARCHAR(20) NOT NULL,
    remark VARCHAR(100),
    encrypted_cookies TEXT NOT NULL,
    iv VARCHAR(32) NOT NULL,
    status VARCHAR(20) DEFAULT 'pending',
    last_checked_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_accounts_user_id (user_id),
    INDEX idx_accounts_status (status),
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Tasks table
CREATE TABLE IF NOT EXISTS tasks (
    id CHAR(36) PRIMARY KEY,
    account_id CHAR(36) NOT NULL,
    cron_expression VARCHAR(50) NOT NULL,
    is_enabled BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_tasks_account_id (account_id),
    INDEX idx_tasks_is_enabled (is_enabled),
    FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Signin logs table
CREATE TABLE IF NOT EXISTS signin_logs (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    account_id CHAR(36) NOT NULL,
    topic_title VARCHAR(100),
    status VARCHAR(20) NOT NULL,
    reward_info JSON,
    error_message TEXT,
    signed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_signin_logs_account_id (account_id),
    INDEX idx_signin_logs_signed_at (signed_at),
    INDEX idx_signin_logs_status (status),
    FOREIGN KEY (account_id) REFERENCES accounts(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
