import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql";
import { waitlistSignups } from "../src/db/schema/waitlist.js";
import * as schema from "../src/db/schema/index.js";
import { writeFile } from "fs/promises";

const DB_URL = process.env.TURSO_DATABASE_URL;
const AUTH_TOKEN = process.env.TURSO_AUTH_TOKEN;

if (!DB_URL) {
  console.error("TURSO_DATABASE_URL is required");
  process.exit(1);
}

async function exportWaitlist() {
  const client = createClient({ url: DB_URL, authToken: AUTH_TOKEN });
  const db = drizzle(client, { schema });

  const signups = await db.select().from(waitlistSignups).orderBy(waitlistSignups.createdAt);

  if (signups.length === 0) {
    console.log("No waitlist signups found.");
    await client.close();
    return;
  }

  const jsonData = signups.map(s => ({
    id: s.id,
    email: s.email,
    name: s.name,
    source: s.source,
    status: s.status,
    metadata: s.metadata ? JSON.parse(s.metadata) : null,
    createdAt: s.createdAt,
    updatedAt: s.updatedAt,
  }));

  const csvHeader = "id,email,name,source,status,metadata,createdAt,updatedAt";
  const csvRows = signups.map(s => {
    const meta = s.metadata ? `"${s.metadata.replace(/"/g, '""')}"` : "";
    return `${s.id},"${s.email}","${s.name || ""}","${s.source}","${s.status}",${meta},"${s.createdAt}","${s.updatedAt}"`;
  });
  const csv = [csvHeader, ...csvRows].join("\n");

  await writeFile("waitlist-export.json", JSON.stringify(jsonData, null, 2));
  await writeFile("waitlist-export.csv", csv);

  console.log(`Exported ${signups.length} signups`);
  console.log("  waitlist-export.json");
  console.log("  waitlist-export.csv");

  await client.close();
}

exportWaitlist().catch(err => {
  console.error("Export failed:", err.message);
  process.exit(1);
});
