#!/usr/bin/env node

import { URL } from "node:url";
import { loadWorkspaceEnv, resolveWorkspaceEnvPath } from "./load-env.mjs";

const envPath = loadWorkspaceEnv();
const expectedDatabase = process.argv[2] ?? "capakraken";
const rawUrl = process.env.DATABASE_URL;

if (!rawUrl) {
  console.error(`DATABASE_URL is not configured. Expected it from ${envPath ?? resolveWorkspaceEnvPath()}.`);
  process.exit(1);
}

let parsed;
try {
  parsed = new URL(rawUrl);
} catch (error) {
  console.error(`DATABASE_URL is invalid: ${error instanceof Error ? error.message : String(error)}`);
  process.exit(1);
}

const databaseName = parsed.pathname.replace(/^\/+/, "");
const target = `${parsed.protocol}//${decodeURIComponent(parsed.username)}@${parsed.hostname}${parsed.port ? `:${parsed.port}` : ""}/${databaseName}`;

if (!databaseName) {
  console.error(`DATABASE_URL does not contain a database name. Target=${target}`);
  process.exit(1);
}

if (databaseName !== expectedDatabase) {
  console.error(`Unexpected database target '${databaseName}'. Expected '${expectedDatabase}'. Target=${target}`);
  process.exit(1);
}

console.log(`DB target OK: ${target}`);
