-- Weibo-HotSign Database Initialization Script for MySQL
-- Create tables according to development document specification

-- Users table
CREATE TABLE IF NOT EXISTS users (
    id CHAR(36) PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    hashed_password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT TRUE
);

-- 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,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- 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,
    FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
);

-- 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,
    FOREIGN KEY (account_id) REFERENCES accounts(id)
);

-- Create indexes for better performance
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_accounts_user_id ON accounts(user_id);
CREATE INDEX idx_accounts_status ON accounts(status);
CREATE INDEX idx_tasks_account_id ON tasks(account_id);
CREATE INDEX idx_tasks_is_enabled ON tasks(is_enabled);
CREATE INDEX idx_signin_logs_account_id ON signin_logs(account_id);
CREATE INDEX idx_signin_logs_signed_at ON signin_logs(signed_at);
CREATE INDEX idx_signin_logs_status ON signin_logs(status);

-- Insert sample data for testing (optional)
-- Note: UUIDs must be provided by the application
-- INSERT INTO users (id, username, email, hashed_password) VALUES 
-- ('your-uuid-here', 'testuser', 'test@example.com', '$2b$12$hashed_password_here');
