package com.contract.review.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.Statement;

/**
 * 数据库初始化器，在应用启动时执行SQL脚本
 */
@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("开始执行数据库初始化脚本...");
        
        try (Connection connection = dataSource.getConnection();
             InputStream inputStream = getClass().getResourceAsStream("/schema.sql");
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
            
            if (inputStream == null) {
                System.out.println("未找到schema.sql文件");
                return;
            }
            
            StringBuilder sqlBuilder = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.isEmpty() && !line.startsWith("--")) {
                    sqlBuilder.append(line);
                    if (line.endsWith(";")) {
                        String sql = sqlBuilder.toString();
                        try (Statement statement = connection.createStatement()) {
                            statement.execute(sql);
                            System.out.println("执行SQL成功: " + sql.substring(0, Math.min(sql.length(), 100)) + "...");
                        }
                        sqlBuilder.setLength(0);
                    }
                }
            }
            
            System.out.println("数据库初始化脚本执行完成");
        } catch (Exception e) {
            System.out.println("执行数据库初始化脚本时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
