package com.reading.platform.util;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class InitClasses {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://8.148.151.56:3306/reading_platform?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
        String user = "root";
        String password = "reading_platform_pwd";

        String sqlFile = "init-classes.sql";
        String sql = new String(Files.readAllBytes(Paths.get(sqlFile)));

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            System.out.println("Connected to database successfully");

            try (Statement statement = conn.createStatement()) {
                String[] statements = sql.split(";");
                for (String stmt : statements) {
                    String trimmed = stmt.trim();
                    if (!trimmed.isEmpty() && !trimmed.startsWith("--")) {
                        boolean isResultSet = statement.execute(trimmed);
                        if (isResultSet) {
                            try (ResultSet rs = statement.getResultSet()) {
                                ResultSetMetaData meta = rs.getMetaData();
                                while (rs.next()) {
                                    StringBuilder sb = new StringBuilder("  ");
                                    for (int i = 1; i <= meta.getColumnCount(); i++) {
                                        sb.append(meta.getColumnName(i)).append("=").append(rs.getString(i)).append(", ");
                                    }
                                    System.out.println(sb.toString());
                                }
                            }
                        } else {
                            System.out.println("Executed: " + trimmed.substring(0, Math.min(50, trimmed.length())));
                        }
                    }
                }
            }
        }
    }
}
