-- Migration: Initial Schema
-- Version: 20250101_000000
-- Description: 创建初始数据库结构
-- Created: 2025-01-01 00:00:00

-- ==========================================
-- UP Migration (执行迁移)
-- ==========================================

-- 创建用户表
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    salt VARCHAR(32) NOT NULL,
    role ENUM('admin', 'clinic_user') NOT NULL DEFAULT 'clinic_user',
    clinic_id VARCHAR(50),
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_username (username),
    INDEX idx_clinic_id (clinic_id),
    INDEX idx_role (role)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 创建患者表
CREATE TABLE IF NOT EXISTS patients (
    id INT AUTO_INCREMENT PRIMARY KEY,
    case_number VARCHAR(50) NOT NULL UNIQUE,
    name VARCHAR(100) NOT NULL,
    age INT,
    gender ENUM('男', '女', '未知') DEFAULT '未知',
    phone VARCHAR(20),
    clinic_name VARCHAR(100),
    last_visit_date DATE,
    last_doctor VARCHAR(100),
    diagnosis TEXT,
    missed_diagnosis TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_case_number (case_number),
    INDEX idx_name (name),
    INDEX idx_clinic_name (clinic_name),
    INDEX idx_last_visit_date (last_visit_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 创建回访记录表
CREATE TABLE IF NOT EXISTS callback_records (
    id INT AUTO_INCREMENT PRIMARY KEY,
    case_number VARCHAR(50) NOT NULL,
    callback_methods TEXT,
    callback_result VARCHAR(50),
    callback_record TEXT,
    operator VARCHAR(100),
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_case_number (case_number),
    INDEX idx_callback_result (callback_result),
    INDEX idx_operator (operator),
    INDEX idx_create_time (create_time),
    FOREIGN KEY (case_number) REFERENCES patients(case_number) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ==========================================
-- DOWN Migration (回滚迁移)
-- ==========================================

-- 删除回访记录表
DROP TABLE IF EXISTS callback_records;

-- 删除患者表
DROP TABLE IF EXISTS patients;

-- 删除用户表
DROP TABLE IF EXISTS users;

-- ==========================================
-- 验证脚本 (可选)
-- ==========================================

-- 验证表是否创建成功
-- SELECT COUNT(*) FROM information_schema.tables 
-- WHERE table_schema = DATABASE() AND table_name IN ('users', 'patients', 'callback_records');
