-- PerToolBox 数据库初始化脚本
-- Copyright (C) 2024 Sea Network Technology Studio
-- Author: Canglan <admin@sea-studio.top>
-- License: AGPL v3

CREATE DATABASE IF NOT EXISTS toolbox_db
    CHARACTER SET utf8mb4
    COLLATE utf8mb4_unicode_ci;

USE toolbox_db;

-- 用户表
CREATE TABLE IF NOT EXISTS `users` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(50) NULL,
    `phone` VARCHAR(20) NULL,
    `email` VARCHAR(100) NULL,
    `wx_openid` VARCHAR(100) NULL,
    `password_hash` VARCHAR(200) NOT NULL,
    `avatar` VARCHAR(500) NULL,
    `is_active` TINYINT(1) DEFAULT 1,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `last_login` DATETIME NULL,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `idx_phone` (`phone`),
    UNIQUE INDEX `idx_email` (`email`),
    UNIQUE INDEX `idx_wx_openid` (`wx_openid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 待办事项表
CREATE TABLE IF NOT EXISTS `todos` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `user_id` INT NOT NULL,
    `title` VARCHAR(200) NOT NULL,
    `description` TEXT,
    `completed` TINYINT(1) DEFAULT 0,
    `priority` TINYINT DEFAULT 1,
    `category` VARCHAR(50) DEFAULT '学习',
    `due_date` DATETIME,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    INDEX `idx_user_id` (`user_id`),
    INDEX `idx_completed` (`completed`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 便签表
CREATE TABLE IF NOT EXISTS `notes` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `user_id` INT NOT NULL,
    `title` VARCHAR(200) NOT NULL,
    `content` TEXT,
    `tags` JSON,
    `is_archived` TINYINT(1) DEFAULT 0,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    INDEX `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 工具总访问次数表
CREATE TABLE IF NOT EXISTS `tool_stats_total` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `tool_name` VARCHAR(50) NOT NULL,
    `total_count` INT DEFAULT 0,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `idx_tool_name` (`tool_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 插入默认工具记录
INSERT INTO `tool_stats_total` (`tool_name`, `total_count`) VALUES
('todos', 0),
('notes', 0),
('password', 0),
('qrcode', 0),
('crypto_hash', 0),
('crypto_base64', 0),
('crypto_url', 0),
('crypto_aes', 0),
('json', 0)
ON DUPLICATE KEY UPDATE total_count=total_count;

SELECT '数据库初始化完成！' AS message;