import path from "path";

export function resolveDatabasePath(): string {
  const dbUrl = process.env.DATABASE_URL || "file:./data/app.db";

  if (!dbUrl.startsWith("file:")) {
    return path.resolve(process.cwd(), "prisma", "data", "app.db");
  }

  const rawPath = dbUrl.slice("file:".length);

  if (path.isAbsolute(rawPath)) {
    return rawPath;
  }

  // Prisma resolves a relative `file:` URL against the schema directory
  // (prisma/), NOT the cwd. We must resolve it the same way, otherwise we
  // can hand back a stray empty ./data/app.db (created by a cwd-relative
  // `prisma db push`) while the live DB Prisma actually uses sits under
  // prisma/data/ — which made export-db stream a 0-byte file in dev.
  const normalized = rawPath.replace(/^\.\//, "");
  return path.resolve(process.cwd(), "prisma", normalized);
}

export function getTimestampFileSuffix(now: Date = new Date()): string {
  const iso = now.toISOString();
  return iso.replace(/[:.]/g, "-");
}
