import "dotenv/config";
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { users, clients, documents } from "../src/lib/db/schema";
import bcrypt from "bcryptjs";
import { inArray } from "drizzle-orm";

const client = postgres(process.env.DATABASE_URL!);
const db = drizzle({ client });

async function seed() {
  const email = process.env.AGENT_EMAIL;
  const password = process.env.AGENT_PASSWORD;

  if (!email || !password) {
    throw new Error("AGENT_EMAIL and AGENT_PASSWORD env vars are required");
  }

  const passwordHash = await bcrypt.hash(password, 12);

  await db.insert(users).values({ email, passwordHash }).onConflictDoNothing();

  console.log(`Seeded agent account: ${email}`);

  // Seed clients
  await db.insert(clients).values([
    { name: "Sarah Johnson", email: "sarah.j@example.com" },
    { name: "Mike Torres", email: "m.torres@example.com" },
  ]).onConflictDoNothing();

  console.log("Seeded clients: Sarah Johnson, Mike Torres");

  // Query back seeded clients to get their IDs
  const [sarah, mike] = await db
    .select({ id: clients.id })
    .from(clients)
    .where(inArray(clients.email, ["sarah.j@example.com", "m.torres@example.com"]))
    .orderBy(clients.createdAt);

  // Seed placeholder documents
  if (sarah && mike) {
    await db.insert(documents).values([
      { name: "Purchase Agreement - 842 Maple Dr", clientId: sarah.id, status: "Signed", sentAt: new Date("2026-02-15") },
      { name: "Seller Disclosure - 842 Maple Dr", clientId: sarah.id, status: "Signed", sentAt: new Date("2026-02-14") },
      { name: "Buyer Rep Agreement", clientId: mike.id, status: "Sent", sentAt: new Date("2026-03-10") },
      { name: "Purchase Agreement - 1205 Oak Ave", clientId: mike.id, status: "Draft", sentAt: null },
    ]).onConflictDoNothing();

    console.log("Seeded 4 placeholder documents");
  } else {
    console.log("Skipping documents seed — clients not found");
  }

  process.exit(0);
}

seed().catch((err) => {
  console.error(err);
  process.exit(1);
});
