#!/usr/bin/env node

import { loadWorkspaceEnv, resolveWorkspaceEnvPaths } from "./load-env.mjs";
import { getExpectedDatabaseName, inspectDatabaseUrl } from "./db-target-guard.mjs";

const loadedEnvPaths = loadWorkspaceEnv();
const expectedDatabase = process.argv[2] ?? getExpectedDatabaseName();
const rawUrl = process.env.DATABASE_URL;
const expectedEnvSources = loadedEnvPaths.length > 0
  ? loadedEnvPaths.join(", ")
  : resolveWorkspaceEnvPaths().join(", ");

if (!rawUrl) {
  console.error(`DATABASE_URL is not configured. Expected it from one of: ${expectedEnvSources}.`);
  process.exit(1);
}

try {
  const result = inspectDatabaseUrl(rawUrl, expectedDatabase);
  console.log(`DB target OK: ${result.target}`);
} catch (error) {
  console.error(error instanceof Error ? error.message : String(error));
  process.exit(1);
}
