'use strict';

const VALID_DIALECTS = ['postgres', 'mysql', 'oracle', 'sqlite'];

/**
 * Split SQL string from generateDDL() into an array of executable statements.
 *
 * Rules:
 *   - Strip lines starting with `--` (SQL comment) and blank lines outside statements.
 *   - For Oracle: PL/SQL block (BEGIN ... END; followed by `/` on its own line)
 *     is treated as a single statement; the `/` terminator is stripped because
 *     the oracledb driver does not accept it.
 *   - For other dialects: split by `;` at end of line. Trailing semicolons are stripped.
 *
 * @param {string} ddl
 * @param {string} dialect - 'postgres' | 'mysql' | 'oracle' | 'sqlite'
 * @returns {string[]}
 */
function splitStatements(ddl, dialect) {
  if (typeof ddl !== 'string') {
    throw new Error('splitStatements: ddl must be a string');
  }
  if (!VALID_DIALECTS.includes(dialect)) {
    throw new Error(
      `splitStatements: invalid dialect '${dialect}'. ` +
        `Supported: ${VALID_DIALECTS.join(', ')}`
    );
  }

  if (ddl.trim() === '') return [];

  const lines = ddl.split(/\r?\n/);
  const statements = [];
  let current = [];
  let inPlsql = false;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmed = line.trim();

    if (dialect === 'oracle' && inPlsql) {
      if (trimmed === '/') {
        const stmt = current.join('\n').replace(/\s+$/, '');
        if (stmt !== '') statements.push(stmt);
        current = [];
        inPlsql = false;
        continue;
      }
      current.push(line);
      continue;
    }

    if (current.length === 0) {
      if (trimmed === '') continue;
      if (trimmed.startsWith('--')) continue;
    }

    if (dialect === 'oracle' && trimmed === 'BEGIN') {
      inPlsql = true;
      current.push(line);
      continue;
    }

    if (current.length > 0 && trimmed === '') {
      // blank line inside accumulating statement: treat as separator only
      // when statement already terminated; the terminator handler below
      // flushes once `;` is seen, so a blank line here means the last
      // statement was malformed (no semicolon). Skip the blank.
      continue;
    }

    if (trimmed.startsWith('--')) {
      // mid-statement comment line: skip
      continue;
    }

    current.push(line);

    if (trimmed.endsWith(';')) {
      const joined = current.join('\n');
      const stmt = joined.replace(/\s+$/, '').replace(/;$/, '').replace(/\s+$/, '');
      if (stmt !== '') statements.push(stmt);
      current = [];
    }
  }

  if (current.length > 0) {
    const stmt = current.join('\n').replace(/\s+$/, '');
    if (stmt !== '') statements.push(stmt);
  }

  return statements;
}

module.exports = { splitStatements };
