import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import type { FastifyBaseLogger } from "fastify";

function runPrismaCli(rootDir: string, args: string[]) {
  const prismaJs = join(rootDir, "node_modules", "prisma", "build", "index.js");
  if (existsSync(prismaJs)) {
    execFileSync(process.execPath, [prismaJs, ...args], {
      cwd: rootDir,
      stdio: "inherit",
      env: { ...process.env, PRISMA_HIDE_UPDATE_MESSAGE: "1" },
    });
    return;
  }

  throw new Error("Prisma CLI not found at node_modules/prisma/build/index.js. Run `npm install` in /server.");
}

export async function ensureDatabaseReady(logger: FastifyBaseLogger) {
  const rootDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  const startedAt = Date.now();
  logger.info("Applying Prisma migrations...");
  runPrismaCli(rootDir, ["migrate", "deploy"]);
  logger.info({ durationMs: Date.now() - startedAt }, "Prisma migrations applied");
}
