import { defineEventHandler } from 'h3';
import { generateData } from './data.mjs';
import 'pathe';
import 'node:fs';
import 'unenv/runtime/npm/debug';
import 'chalk';
import 'c12';
import 'untyped';
import 'pg';
import 'node:crypto';
import 'mkdirp';
import 'camelcase';
import 'pascalcase';
import 'pluralize';

const defaultCardinality = formatCardinality("0+--0+"), defaultRelationship = "associates with";
function parseColumnComment(comment) {
  const splitChar = "|", lines = comment.split(new RegExp(`(?<!\\\\)[${splitChar}]`)).map((line) => line.replaceAll("\\|", "|")), links = parseLink(lines);
  if (links.succeeded) {
    lines.splice(lines.indexOf(links.linkLine), 1);
    if (links.cardinalityLine)
      lines.splice(lines.indexOf(links.cardinalityLine), 1);
    if (links.relationshipLine)
      lines.splice(lines.indexOf(links.relationshipLine), 1);
  }
  const extraColumns = parseExtraColumns(lines);
  if (extraColumns.succeeded)
    for (const originalLine of extraColumns.originalLines)
      lines.splice(lines.indexOf(originalLine), 1);
  return {
    cardinality: links.succeeded ? links.cardinality : void 0,
    description: lines.filter(Boolean).join(splitChar),
    extraColumns: extraColumns.succeeded ? extraColumns.extraColumns : void 0,
    link: links.succeeded ? links.link : void 0,
    relationship: links.succeeded ? links.relationship : void 0
  };
}
function parseLink(lines) {
  const linkLine = lines.find((line) => line.startsWith("link:") || line.startsWith("link="));
  if (!linkLine)
    return { succeeded: false };
  let cardinalityLine = lines.find((line) => line.startsWith("cardinality:") || line.startsWith("cardinality=")), cardinality = defaultCardinality;
  if (cardinalityLine) {
    const parsedCardinality = cardinalityLine.replace(/^cardinality[:=]/, "");
    if (/^(0\+|1|1\+|01)(--|\.\.)(0\+|1|1\+|01)$/.test(parsedCardinality))
      cardinality = formatCardinality(parsedCardinality);
    else
      cardinalityLine = void 0;
  }
  const relationshipLine = lines.find((line) => line.startsWith("relationship:") || line.startsWith("relationship=")), relationship = (relationshipLine == null ? void 0 : relationshipLine.replace(/^relationship[:=]/, "")) || defaultRelationship;
  return {
    cardinality,
    cardinalityLine,
    link: linkLine.replace(/^link[:=]/, ""),
    linkLine,
    relationship,
    relationshipLine,
    succeeded: true
  };
}
function parseExtraColumns(lines) {
  const extraColumns = {}, originalLines = [];
  for (const line of lines) {
    const match = line.match(/^(?<key>[^:]+):(?<value>.+)/) || line.match(/^(?<key>[^=]+)=(?<value>.+)/);
    if (!match)
      continue;
    let { value } = match.groups;
    const { key } = match.groups;
    if (!key || !value)
      continue;
    try {
      value = JSON.parse(value);
    } catch {
    }
    extraColumns[key.replaceAll(/^\[|]$/g, "")] = value;
    originalLines.push(line);
  }
  if (Object.keys(extraColumns).length === 0)
    return { succeeded: false };
  return {
    extraColumns,
    originalLines,
    succeeded: true
  };
}
function formatCardinality(string) {
  const leftReplacements = {
    "0+": "}o",
    "01": "|o",
    1: "||",
    "1+": "}|"
  }, rightReplacements = {
    "0+": "o{",
    "01": "o|",
    1: "||",
    "1+": "|{"
  }, [left, right] = string.split(/--|\.\./), splitter = string.includes("--") ? "--" : "..";
  return `${leftReplacements[left]}${splitter}${rightReplacements[right]}`;
}

const table = defineEventHandler(async () => {
  const data = await generateData();
  return data.map((database) => {
    const schemas = [...new Set(database.tables.map((table) => table.schema_id))];
    return {
      database_name: database.database,
      database_url: database.hostPort,
      schemas: schemas.map((schema) => {
        var _a;
        const tables = database.tables.filter((table) => table.schema_id === schema);
        return {
          schema_name: (_a = tables[0]) == null ? void 0 : _a.schema_name,
          tables: tables.map((table) => {
            var _a2;
            return {
              columns: (((_a2 = database.classes.find((c) => c.class_id === table.table_id)) == null ? void 0 : _a2.attributes) || []).map((attribute) => {
                if (!attribute.comment) {
                  return {
                    column_default: attribute.default,
                    column_name: attribute.attribute_name,
                    comment: "",
                    data_type: attribute.type_name,
                    is_nullable: !attribute.not_null
                  };
                }
                const parsedComment = parseColumnComment(attribute.comment);
                return {
                  column_default: attribute.default,
                  column_name: attribute.attribute_name,
                  comment: parsedComment.description,
                  data_type: attribute.type_name,
                  is_nullable: !attribute.not_null,
                  ...parsedComment.extraColumns
                };
              }),
              table_name: table.table_name
            };
          })
        };
      })
    };
  });
});

export { table as default };
//# sourceMappingURL=table.mjs.map
