import { PrismaMssql } from "@prisma/adapter-mssql";
import { PrismaClient } from "./generated/prisma/client";
import { writeFileSync } from "node:fs";

const outputPath =
  process.argv[2] ??
  process.env.CONFIG_OUTPUT_FILE ??
  "configurations-first-10-with-relations.json";

const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
  throw new Error("DATABASE_URL is not set.");
}

const adapter = new PrismaMssql(connectionString);
const prisma = new PrismaClient({ adapter });

try {
  const configurations = await prisma.configuration.findMany({
    take: 10,
    orderBy: { configRecId: "asc" },
    include: {
      configStatus: true,
      configurationAudits: {
        orderBy: { lastUpdatedUtc: "desc" },
        include: {
          configurationValues: {
            orderBy: { configurationAuditValueRecId: "asc" },
          },
        },
      },
    },
  });

  if (configurations.length === 0) {
    console.error("No configurations found.");
    process.exit(1);
  }

  writeFileSync(outputPath, JSON.stringify(configurations, null, 2));
} finally {
  await prisma.$disconnect();
}
