import { readFileSync } from "node:fs";
import path from "node:path";
import { Client } from "pg";
function resolveAppRoot() {
  const fromEnv = process.env.OM_TEST_APP_ROOT?.trim();
  return fromEnv ? path.resolve(fromEnv) : path.resolve(process.cwd(), "apps/mercato");
}
function readEnvValue(key) {
  if (process.env[key]) return process.env[key];
  const candidatePaths = [
    path.resolve(resolveAppRoot(), ".env"),
    path.resolve(process.cwd(), "apps/mercato/.env"),
    path.resolve(process.cwd(), ".env")
  ];
  for (const envPath of candidatePaths) {
    try {
      const content = readFileSync(envPath, "utf-8");
      const match = content.match(new RegExp(`^${key}=(.+)$`, "m"));
      if (match?.[1]) return match[1].trim();
    } catch {
      continue;
    }
  }
  return void 0;
}
function resolveDatabaseUrl() {
  const url = readEnvValue("DATABASE_URL");
  if (!url) throw new Error("[internal] DATABASE_URL is not configured for integration DB fixtures");
  return url;
}
async function withClient(run) {
  const client = new Client({ connectionString: resolveDatabaseUrl() });
  await client.connect();
  try {
    return await run(client);
  } finally {
    await client.end();
  }
}
async function clearUserHomeOrganization(userId) {
  await withClient(async (client) => {
    await client.query("update users set organization_id = null where id = $1", [userId]);
  });
}
async function setUserAclInDb(input) {
  await withClient(async (client) => {
    const existing = await client.query(
      "select id from user_acls where user_id = $1 and tenant_id = $2 limit 1",
      [input.userId, input.tenantId]
    );
    const featuresJson = JSON.stringify(input.features);
    const organizationsJson = input.organizations === null ? null : JSON.stringify(input.organizations);
    if (existing.rows.length > 0) {
      await client.query(
        "update user_acls set features_json = $2::jsonb, organizations_json = $3::jsonb, is_super_admin = false, updated_at = now() where id = $1",
        [existing.rows[0].id, featuresJson, organizationsJson]
      );
      return;
    }
    await client.query(
      `insert into user_acls (id, user_id, tenant_id, features_json, organizations_json, is_super_admin, created_at)
       values (gen_random_uuid(), $1, $2, $3::jsonb, $4::jsonb, false, now())`,
      [input.userId, input.tenantId, featuresJson, organizationsJson]
    );
  });
}
async function deleteUserAclInDb(userId) {
  if (!userId) return;
  await withClient(async (client) => {
    await client.query("delete from user_acls where user_id = $1", [userId]);
  });
}
async function createOrganizationInDb(input) {
  return withClient(async (client) => {
    const result = await client.query(
      `insert into organizations
         (id, tenant_id, name, is_active, ancestor_ids, child_ids, descendant_ids, depth, created_at, updated_at)
       values (gen_random_uuid(), $1, $2, true, '[]'::jsonb, '[]'::jsonb, '[]'::jsonb, 0, now(), now())
       returning id`,
      [input.tenantId, input.name]
    );
    return result.rows[0].id;
  });
}
async function deleteOrganizationInDb(organizationId) {
  if (!organizationId) return;
  await withClient(async (client) => {
    await client.query("delete from organizations where id = $1", [organizationId]);
  });
}
async function deleteIntegrationCredentialsInDb(organizationId) {
  if (!organizationId) return;
  await withClient(async (client) => {
    await client.query("delete from integration_credentials where organization_id = $1", [organizationId]);
  });
}
export {
  clearUserHomeOrganization,
  createOrganizationInDb,
  deleteIntegrationCredentialsInDb,
  deleteOrganizationInDb,
  deleteUserAclInDb,
  setUserAclInDb,
  withClient
};
//# sourceMappingURL=dbFixtures.js.map
