const { execSync } = require("child_process");
const path = require("path");
const fs = require("fs");

async function main() {
  try {
    // Ensure Prisma client directory exists and has correct permissions
    const prismaClientDir = path.join(process.cwd(), "node_modules", ".prisma");
    if (!fs.existsSync(prismaClientDir)) {
      fs.mkdirSync(prismaClientDir, { recursive: true });
    }
    const clientDir = path.join(prismaClientDir, "client");
    if (!fs.existsSync(clientDir)) {
      fs.mkdirSync(clientDir, { recursive: true });
    }

    // Reset the database in development
    if (process.env.NODE_ENV === "development") {
      console.log("🔄 Resetting database...");
      execSync("npx prisma migrate reset --force", { stdio: "inherit" });
    }

    // Run migrations
    console.log("🚀 Running migrations...");
    execSync("npx prisma migrate deploy", { stdio: "inherit" });

    // Generate Prisma Client
    console.log("⚡ Generating Prisma Client...");
    try {
      execSync("npx prisma generate", { stdio: "inherit" });
    } catch (error) {
      console.warn("⚠️ Warning: Could not generate Prisma client, but continuing...");
      console.warn("This is expected if the client was already generated during build.");
    }

    console.log("✅ Database setup completed successfully!");
  } catch (error) {
    console.error("❌ Error during database setup:", error);
    process.exit(1);
  }
}

main();
