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

const databaseUrl = Bun.env.DATABASE_URL;

if (!databaseUrl) {
  throw new Error("DATABASE_URL is not set.");
}

const adapter = new PrismaMssql(databaseUrl, { schema: "dbo" });
const prisma = new PrismaClient({ adapter });

async function exportProducts() {
  console.log("Fetching products with relations...");

  const products = await prisma.productCatalog.findMany({
    where: {
      inactiveFlag: false,
    },
    include: {
      subcategory: {
        include: {
          category: true,
        },
      },
      manufacturer: true,
      inventory: true,
      itemVendors: true,
    },
    take: 100,
  });

  const jsonData = JSON.stringify(products, null, 2);

  writeFileSync("products-with-relations.json", jsonData);

  console.log(
    `Exported ${products.length} products to products-with-relations.json`,
  );

  await prisma.$disconnect();
}

exportProducts().catch(console.error);
