исправь ошибки // sqlProcessor.js
const { Database } = require('./db');

// Функции парсинга и оценки WHERE
function parseSQL(command) {
  const joinRegex = /^SELECT\s+(.+)\s+FROM\s+(\w+)\s+JOIN\s+(\w+)\s+ON\s+(\w+\.\w+)\s*=\s*(\w+\.\w+)(?:\s+WHERE\s+(.+?))?(?:\s+ORDER\s+BY\s+(\w+)\s+(ASC|DESC))?;?$/i;
  const selectRegex = /^SELECT\s+(.+)\s+FROM\s+(\w+)(?:\s+WHERE\s+(.+?))?(?:\s+ORDER\s+BY\s+(\w+)\s+(ASC|DESC))?;?$/i;
  // Улучшенный regex для INSERT, учитывающий кавычки
  const insertRegex = /^INSERT\s+INTO\s+(\w+)\s*\(([^)]+)\)\s+VALUES\s*\((.+)\);?$/i;
  const updateRegex = /^UPDATE\s+(\w+)\s+SET\s+([^;]+?)(?:\s+WHERE\s+(\w+)\s*=\s*(\d+))?;?$/i;
  const deleteRegex = /^DELETE\s+FROM\s+(\w+)(?:\s+WHERE\s+(\w+)\s*=\s*(\d+))?;?$/i;

  let match = command.match(joinRegex);
  if (match) {
    const fields = match[1].split(',').map(f => f.trim());
    const table1 = match[2];
    const table2 = match[3];
    const joinConditionLeft = match[4];
    const joinConditionRight = match[5];
    const whereClause = match[6];
    const orderField = match[7];
    const orderDirection = match[8] ? match[8].toUpperCase() : 'ASC';

    const where = whereClause ? parseWhere(whereClause) : null;
    const order = orderField ? { field: orderField, direction: orderDirection } : null;

    return { 
      type: 'JOIN',
      fields, 
      table1, 
      table2, 
      joinCondition: { left: joinConditionLeft, right: joinConditionRight },
      where, 
      order 
    };
  }

  match = command.match(selectRegex);
  if (match) {
    const fields = match[1].split(',').map(f => f.trim());
    const tableName = match[2];
    const whereClause = match[3];
    const orderField = match[4];
    const orderDirection = match[5] ? match[5].toUpperCase() : 'ASC';

    const where = whereClause ? parseWhere(whereClause) : null;
    const order = orderField ? { field: orderField, direction: orderDirection } : null;

    return { type: 'SELECT', tableName, fields, where, order };
  }

  match = command.match(insertRegex);
  if (match) {
    const tableName = match[1];
    const fields = match[2].split(',').map(f => f.trim());
    const rawValues = match[3].trim();

    // Использование регулярных выражений для корректного разбиения значений
    const values = [];
    const regex = /(".*?"|'.*?'|[^,]+)(?=\s*,|\s*$)/g;
    let valueMatch;
    while ((valueMatch = regex.exec(rawValues)) !== null) {
      let val = valueMatch[1].trim();
      if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
        val = val.slice(1, -1);
      } else if (!isNaN(Number(val))) {
        val = Number(val);
      }
      values.push(val);
    }

    if (fields.length !== values.length) {
      throw new Error('Количество полей и значений не совпадает.');
    }

    const record = {};
    fields.forEach((field, index) => {
      record[field] = values[index];
    });
    return { type: 'INSERT', tableName, values: record };
  }

  match = command.match(updateRegex);
  if (match) {
    const tableName = match[1];
    const setClause = match[2];
    const whereField = match[3];
    const whereValue = whereField ? Number(match[4]) : null;

    const fields = {};
    setClause.split(',').forEach(clause => {
      const [field, value] = clause.split('=').map(s => s.trim());
      if (isNaN(Number(value))) {
        fields[field] = value.replace(/['"]/g, '');
      } else {
        fields[field] = Number(value);
      }
    });

    const where = whereField && whereValue !== null ? { field: whereField, operator: '=', value: whereValue, id: whereValue } : null;

    return { type: 'UPDATE', tableName, fields, where };
  }

  match = command.match(deleteRegex);
  if (match) {
    const tableName = match[1];
    const whereField = match[2];
    const whereValue = whereField ? Number(match[3]) : null;

    const where = whereField && whereValue !== null ? { field: whereField, operator: '=', value: whereValue, id: whereValue } : null;

    return { type: 'DELETE', tableName, where };
  }

  return null;
}

function parseWhere(whereClause) {
  const operators = ['>=', '<=', '!=', '=', '>', '<'];
  for (let op of operators) {
    const parts = whereClause.split(op);
    if (parts.length === 2) {
      const field = parts[0].trim();
      let value = parts[1].trim();
      if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
        value = value.slice(1, -1);
      }
      if (!isNaN(Number(value))) {
        value = Number(value);
      }
      // Дополнительно, если используется WHERE для идентификатора
      if (field.toLowerCase() === 'id') {
        return { field, operator: op, value, id: value };
      }
      return { field, operator: op, value };
    }
  }
  return null;
}

function evaluateWhere(record, where) {
  const { field, operator, value } = where;
  const recordValue = record[field];
  switch (operator) {
    case '=':
      return recordValue === value;
    case '!=':
      return recordValue !== value;
    case '>':
      return recordValue > value;
    case '<':
      return recordValue < value;
    case '>=':
      return recordValue >= value;
    case '<=':
      return recordValue <= value;
    default:
      return false;
  }
}

async function executeSQLCommand(db, command) {
  const parsed = parseSQL(command);
  if (!parsed) {
    throw new Error('Некорректная команда.');
  }

  const { type } = parsed;

  switch (type.toUpperCase()) {
    case 'SELECT':
      if (parsed.type === 'JOIN') {
        return db.selectQuery(parsed.table1, parsed.fields, parsed.where, parsed.order, parsed);
      }
      return db.selectQuery(parsed.tableName, parsed.fields, parsed.where, parsed.order);
    case 'INSERT':
      await db.insert(parsed.tableName, parsed.values);
      return { inserted: 1 };
    case 'UPDATE':
      const updated = await db.updateRecord(parsed.tableName, parsed.where.id, parsed.fields);
      return { updated: updated ? 1 : 0 };
    case 'DELETE':
      const deleted = await db.deleteRecord(parsed.tableName, parsed.where.id);
      return { deleted: deleted ? 1 : 0 };
    default:
      throw new Error(`Неизвестный тип команды "${type}".`);
  }
}

// Метод для поддержки SQL-команд в классе Database
Database.prototype.selectQuery = function(tableName, selectedFields = ['*'], where = null, order = null, join = null) {
  const table = this.tables.get(tableName);
  if (!table) {
    throw new Error(`Таблица "${tableName}" не найдена.`);
  }

  let records = table.getAll();

  // Если есть JOIN
  if (join) {
    const joinTable = this.tables.get(join.table2);
    if (!joinTable) {
      throw new Error(`Таблица для JOIN "${join.table2}" не найдена.`);
    }

    const [leftField] = join.joinCondition.left.split('.');
    const [rightField] = join.joinCondition.right.split('.');

    const joinRecords = joinTable.getAll();

    // Выполнение INNER JOIN
    records = records.flatMap(record1 => {
      return joinRecords.filter(record2 => record1[leftField] === record2[rightField])
                        .map(record2 => ({ ...record1, ...record2 }));
    });
  }

  // Применение WHERE
  if (where) {
    records = records.filter(record => evaluateWhere(record, where));
  }

  // Применение ORDER BY
  if (order) {
    const { field, direction } = order;
    if (!records[0] || !(field in records[0])) {
      throw new Error(`Поле "${field}" не найдено в результирующем наборе данных.`);
    }
    records.sort((a, b) => {
      if (a[field] < b[field]) return direction === 'ASC' ? -1 : 1;
      if (a[field] > b[field]) return direction === 'ASC' ? 1 : -1;
      return 0;
    });
  }

  // Выбор полей
  if (!(selectedFields.length === 1 && selectedFields[0] === '*')) {
    records = records.map(record => {
      const selected = {};
      selectedFields.forEach(field => {
        if (!(field in record)) {
          throw new Error(`Поле "${field}" не найдено в таблицах.`);
        }
        selected[field] = record[field];
      });
      return selected;
    });
  }

  return records;
}

module.exports = { executeSQLCommand };