import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql";
import { waitlistSignups } from "../src/db/schema/waitlist";
import * as schema from "../src/db/schema";
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");
  console.error("Set it via environment variable or .env file");
  process.exit(1);
}

async function exportWaitlist() {
  const client = createClient({ url: DB_URL!, authToken: AUTH_TOKEN ?? undefined });
  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;
  }

  console.log(`Found ${signups.length} signups\n`);

  // JSON export
  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,
  }));

  // CSV export
  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");

  const jsonFile = "waitlist-export.json";
  const csvFile = "waitlist-export.csv";

  await writeFile(jsonFile, JSON.stringify(jsonData, null, 2));
  await writeFile(csvFile, csv);

  console.log(`Exported ${signups.length} signups`);
  console.log(`  JSON: ${jsonFile}`);
  console.log(`  CSV:  ${csvFile}`);

  await client.close();
}

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