import path from "path";
import { existsSync } from "fs";

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;
  }

  const normalized = rawPath.replace(/^\.\//, "");
  const directPath = path.resolve(process.cwd(), normalized);
  if (existsSync(directPath)) {
    return directPath;
  }

  const prismaPath = path.resolve(process.cwd(), "prisma", normalized);
  return prismaPath;
}

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