import { and, eq, like, notExists } from "drizzle-orm";
import { nanoid } from "nanoid";

import { auth } from "../lib/auth";
import { db } from "../lib/db";
import { member, organization, sites, user } from "../lib/db/schema";

const TEST_EMAIL = `smoke-sites-${nanoid(8)}@elevaseo.com`;
const TEST_NAME = "Smoke Sites";
const TEST_PASSWORD = "SmokeSites1234!";

async function main() {
  console.log(`→ Signing up ${TEST_EMAIL}`);
  const res = await auth.api.signUpEmail({
    body: { name: TEST_NAME, email: TEST_EMAIL, password: TEST_PASSWORD },
  });
  const userId = res.user.id;

  try {
    // Resolve the user's auto-created Personal Org id (from Phase 1).
    const mem = await db.select().from(member).where(eq(member.userId, userId)).limit(1);
    if (mem.length === 0) throw new Error("Personal org missing — Phase 1 hook may be broken");
    const orgId = mem[0]!.organizationId;
    console.log(`→ Org: ${orgId}`);

    // Directly insert a site as if /api/sites POST ran with this user's active org.
    const siteId = nanoid();
    await db.insert(sites).values({
      id: siteId,
      organizationId: orgId,
      createdByUserId: userId,
      hostname: "example.com",
      url: "https://example.com/",
      label: null,
      createdAt: new Date().toISOString(),
    });

    // Read it back filtered by org (the prod query pattern).
    const found = await db
      .select()
      .from(sites)
      .where(and(eq(sites.organizationId, orgId), eq(sites.id, siteId)));
    if (found.length !== 1) throw new Error(`Expected 1 site, got ${found.length}`);
    if (found[0]!.createdByUserId !== userId) {
      throw new Error(`createdByUserId mismatch: got ${found[0]!.createdByUserId}`);
    }
    console.log(`✓ Site round-trip OK: id=${siteId}`);

    // Assert the row shape no longer carries a stale userId field.
    const keys = Object.keys(found[0]!);
    if (keys.includes("userId")) {
      throw new Error("Stale userId field present on site row");
    }
    if (!keys.includes("organizationId")) {
      throw new Error("organizationId field missing from site row");
    }
    console.log(`✓ Row shape OK: ${keys.join(",")}`);
  } finally {
    // Cleanup: delete the user (cascades member; site cascades via org).
    // Then sweep any orphan personal orgs we created.
    await db.delete(user).where(eq(user.id, userId));
    await db
      .delete(organization)
      .where(
        and(
          like(organization.name, "Personal — smoke-sites-%"),
          notExists(
            db
              .select({ one: member.id })
              .from(member)
              .where(eq(member.organizationId, organization.id)),
          ),
        ),
      );
    console.log(`→ Cleanup done`);
  }

  console.log(`✅ verify-org-sites OK`);
  process.exit(0);
}

main().catch((e) => {
  console.error(`❌ verify-org-sites FAILED:`, e instanceof Error ? e.message : e);
  process.exit(1);
});
