import * as fs from "fs";
import * as path from "path";
import { Pool } from "pg";
import * as dotenv from "dotenv";

dotenv.config({ path: path.join(__dirname, "../../.env") });

async function seed() {
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
  const client = await pool.connect();

  try {
    const files = fs.readdirSync(__dirname).filter((f) => f.endsWith(".sql")).sort();
    console.log(`Running ${files.length} seed file(s)...`);

    for (const file of files) {
      const sql = fs.readFileSync(path.join(__dirname, file), "utf8");
      await client.query(sql);
      console.log(`  ran   ${file}`);
    }

    console.log("Seed complete.");
  } finally {
    client.release();
    await pool.end();
  }
}

seed().catch((err) => {
  console.error("Seed failed:", err);
  process.exit(1);
});
