-- CursorPro 数据库初始化脚本
-- 如果需要手动建表可以使用此脚本，FastAPI 启动时会自动创建表

SET NAMES utf8mb4;
SET CHARACTER SET utf8mb4;

-- 创建数据库（如果不存在）
CREATE DATABASE IF NOT EXISTS cursorpro
    CHARACTER SET utf8mb4
    COLLATE utf8mb4_unicode_ci;

USE cursorpro;

-- cursor_accounts 表
CREATE TABLE IF NOT EXISTS cursor_accounts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL UNIQUE,
    access_token TEXT NOT NULL,
    refresh_token TEXT,
    workos_session_token TEXT,
    membership_type ENUM('free', 'pro') DEFAULT 'pro',
    status ENUM('active', 'in_use', 'disabled', 'expired') DEFAULT 'active',
    usage_count INT DEFAULT 0,
    current_key_id INT,
    last_used_at DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_status (status),
    INDEX idx_membership_type (membership_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- activation_keys 表
CREATE TABLE IF NOT EXISTS activation_keys (
    id INT AUTO_INCREMENT PRIMARY KEY,
    `key` VARCHAR(64) NOT NULL UNIQUE,
    switch_limit INT DEFAULT 100,
    switch_count INT DEFAULT 0,
    membership_type ENUM('free', 'pro') DEFAULT 'pro',
    status ENUM('active', 'disabled') DEFAULT 'active',
    current_account_id INT,
    expire_at DATETIME,
    remark VARCHAR(255),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_key (`key`),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- usage_logs 表
CREATE TABLE IF NOT EXISTS usage_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    key_id INT NOT NULL,
    account_id INT,
    action ENUM('verify', 'switch') NOT NULL,
    ip_address VARCHAR(45),
    success BOOLEAN DEFAULT TRUE,
    message VARCHAR(255),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_key_id (key_id),
    INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 插入示例激活码（可选）
-- INSERT INTO activation_keys (`key`, switch_limit, membership_type) VALUES ('TEST-KEY-0001', 100, 'pro');
