#!/bin/bash

# 数据库迁移脚本

echo "==========================================="
echo "开始执行数据库迁移..."
echo "==========================================="

cd /Users/retirado/Program/ccProgram_0312/lesingle-edu-reading-platform-backend

# 创建临时迁移 Java 文件
cat > /tmp/DbMigrate.java << 'EOF'
import java.sql.*;

public class DbMigrate {
    public static void main(String[] args) {
        String url = "jdbc:mysql://8.148.151.56:3306/reading_platform?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String user = "root";
        String password = "reading_platform_pwd";

        String[] sqls = {
            "CREATE TABLE IF NOT EXISTS course_package (id BIGINT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL COMMENT '套餐名称', description TEXT COMMENT '套餐描述', price BIGINT NOT NULL COMMENT '价格（分）', discount_price BIGINT COMMENT '折后价格（分）', discount_type VARCHAR(50) COMMENT '折扣类型', grade_levels VARCHAR(500) COMMENT '适用年级', course_count INT NOT NULL DEFAULT 0 COMMENT '课程数量', status VARCHAR(50) NOT NULL DEFAULT 'DRAFT' COMMENT '状态', submitted_at DATETIME COMMENT '提交时间', submitted_by BIGINT COMMENT '提交人ID', reviewed_at DATETIME COMMENT '审核时间', reviewed_by BIGINT COMMENT '审核人ID', review_comment TEXT COMMENT '审核意见', published_at DATETIME COMMENT '发布时间', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_status (status)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='课程套餐表')",

            "CREATE TABLE IF NOT EXISTS course_package_course (id BIGINT NOT NULL AUTO_INCREMENT, package_id BIGINT NOT NULL COMMENT '套餐ID', course_id BIGINT NOT NULL COMMENT '课程ID', grade_level VARCHAR(50) COMMENT '适用年级', sort_order INT NOT NULL DEFAULT 0 COMMENT '排序号', PRIMARY KEY (id), UNIQUE KEY uk_package_course (package_id, course_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='套餐课程关联表'",

            "CREATE TABLE IF NOT EXISTS tenant_package (id BIGINT NOT NULL AUTO_INCREMENT, tenant_id BIGINT NOT NULL COMMENT '租户ID', package_id BIGINT NOT NULL COMMENT '套餐ID', start_date DATE NOT NULL COMMENT '开始日期', end_date DATE NOT NULL COMMENT '结束日期', price_paid BIGINT NOT NULL DEFAULT 0 COMMENT '实付价格', status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE' COMMENT '状态', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_tenant_id (tenant_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='租户套餐关联表'",

            "CREATE TABLE IF NOT EXISTS course_lesson (id BIGINT NOT NULL AUTO_INCREMENT, course_id BIGINT NOT NULL COMMENT '课程ID', lesson_type VARCHAR(50) NOT NULL COMMENT '课程类型', name VARCHAR(255) NOT NULL COMMENT '课程名称', description TEXT COMMENT '课程描述', duration INT COMMENT '时长（分钟）', video_path VARCHAR(500) COMMENT '视频路径', video_name VARCHAR(255) COMMENT '视频名称', ppt_path VARCHAR(500) COMMENT 'PPT路径', ppt_name VARCHAR(255) COMMENT 'PPT名称', pdf_path VARCHAR(500) COMMENT 'PDF路径', pdf_name VARCHAR(255) COMMENT 'PDF名称', objectives TEXT COMMENT '教学目标', preparation TEXT COMMENT '教学准备', extension TEXT COMMENT '教学延伸', reflection TEXT COMMENT '教学反思', assessment_data TEXT COMMENT '评测数据', use_template TINYINT(1) DEFAULT 0 COMMENT '是否使用模板', sort_order INT NOT NULL DEFAULT 0 COMMENT '排序号', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_course_id (course_id), UNIQUE KEY uk_course_lesson_type (course_id, lesson_type)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='课程环节表'",

            "CREATE TABLE IF NOT EXISTS lesson_step (id BIGINT NOT NULL AUTO_INCREMENT, lesson_id BIGINT NOT NULL COMMENT '课程环节ID', name VARCHAR(255) NOT NULL COMMENT '环节名称', content TEXT COMMENT '环节内容', duration INT NOT NULL DEFAULT 5 COMMENT '时长（分钟）', objective TEXT COMMENT '教学目标', resource_ids TEXT COMMENT '资源ID列表', sort_order INT NOT NULL DEFAULT 0 COMMENT '排序号', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_lesson_id (lesson_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='教学环节表'",

            "CREATE TABLE IF NOT EXISTS lesson_step_resource (id BIGINT NOT NULL AUTO_INCREMENT, step_id BIGINT NOT NULL COMMENT '环节ID', resource_id BIGINT NOT NULL COMMENT '资源ID', sort_order INT NOT NULL DEFAULT 0 COMMENT '排序号', PRIMARY KEY (id), KEY idx_step_id (step_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='环节资源关联表'",

            "CREATE TABLE IF NOT EXISTS theme (id BIGINT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL COMMENT '主题名称', description TEXT COMMENT '主题描述', sort_order INT NOT NULL DEFAULT 0 COMMENT '排序号', status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE' COMMENT '状态', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY idx_status (status)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='主题字典表'"
        };

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement()) {

            for (int i = 0; i < sqls.length; i++) {
                try {
                    System.out.println("执行 SQL [" + (i + 1) + "/" + sqls.length + "]...");
                    stmt.execute(sqls[i]);
                    System.out.println("✓ 成功");
                } catch (SQLException e) {
                    if (e.getMessage() != null && e.getMessage().contains("already exists")) {
                        System.out.println("⚠ 表已存在，跳过");
                    } else {
                        System.out.println("✗ 失败: " + e.getMessage());
                    }
                }
            }

            System.out.println("\n===========================================");
            System.out.println("数据库迁移完成！");
            System.out.println("===========================================");

        } catch (SQLException e) {
            System.err.println("数据库连接失败: " + e.getMessage());
            System.exit(1);
        }
    }
}
EOF

# 编译并运行
echo "编译迁移工具..."
javac /tmp/DbMigrate.java 2>&1 || {
    echo "编译失败，尝试使用 Maven..."
    # 使用 Maven 创建临时项目
    mvn exec:java -Dexec.mainClass="DbMigrate" -Dexec.classpathScope=compile -Dexec.cleanup=false -q 2>&1 || {
        echo "Maven 方式也失败，尝试直接使用 mvn spring-boot:run..."
        # 修改 Application 主类临时添加迁移
        echo "请手动执行以下步骤："
        echo "1. 打开 Navicat 或其他数据库管理工具"
        echo "2. 连接到数据库：8.148.151.56:3306"
        echo "3. 执行 SQL 脚本：src/main/resources/db/migration/V20260312__create_new_tables.sql"
        exit 1
    }
}

echo "执行迁移..."
java -cp /tmp DbMigrate

echo "清理临时文件..."
rm -f /tmp/DbMigrate.*
