import crypto from "crypto";
import path from "path";

export function buildDatabaseUrl(infra, dbName) {
  return `postgresql://${encodeURIComponent(infra.user)}:${encodeURIComponent(infra.password)}@${infra.host}:${infra.port}/${dbName}?sslmode=disable`;
}

export function buildContainerName(productDir) {
  return limitIdentifier(
    `testkit_pg_${slugSegment(path.basename(productDir))}_${hashString(productDir, 10)}`,
    63
  );
}

export function buildTemplateDatabaseName(serviceName, fingerprint) {
  return limitIdentifier(
    `tk_tpl_${slugSegment(serviceName)}_${fingerprint.slice(0, 16)}`,
    63
  );
}

export function buildRuntimeDatabaseName(serviceName, bindingKey, fingerprint) {
  return limitIdentifier(
    `tk_${slugSegment(serviceName)}_${hashString(bindingKey, 10)}_${fingerprint.slice(0, 12)}`,
    63
  );
}

export function hashString(value, length = 12) {
  return crypto.createHash("sha256").update(value).digest("hex").slice(0, length);
}

export function slugSegment(value) {
  return value.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "db";
}

export function limitIdentifier(value, maxLength) {
  return value.length <= maxLength ? value : value.slice(0, maxLength);
}

export function escapeIdentifier(value) {
  return String(value).replace(/"/g, "\"\"");
}

export function escapeSqlLiteral(value) {
  return String(value).replace(/'/g, "''");
}
