// ── Splitting a .sql file into statements ──────────────────────────────────
//
// Extracted from utils/db.js so that core's schema.sql and a module's schema
// fragment are split by literally the same code. MODULE_API.md §2.6 promises a
// fragment is replayed "statement by statement, split the same way" — with two
// copies of this that promise would hold only until one of them was edited.
//
// It lives in its own file rather than being exported from utils/db.js because
// modules/loader.js validates fragments at require time and must not pull the
// mariadb pool into app.js's require chain to do it.

/**
 * Split a .sql file into individual statements.
 *
 * Strips `--` comments (full-line AND trailing) before splitting — so a leading
 * comment block doesn't get glued onto the statement that follows it, and a `;`
 * inside a trailing comment can't chop a statement in half. Safe because neither
 * core's schema nor a conforming fragment puts `--` inside a string literal
 * (§2.6 states that as a rule a fragment must follow).
 *
 * @param {string} sql
 * @returns {string[]} non-empty, trimmed statements in file order
 */
function splitStatements(sql) {
  return sql
    .split('\n')
    .map((line) => {
      const i = line.indexOf('--')
      return i === -1 ? line : line.slice(0, i)
    })
    .join('\n')
    .split(';')
    .map((s) => s.trim())
    .filter((s) => s.length > 0)
}

module.exports = { splitStatements }
