import { eq } from "drizzle-orm";
import { nanoid } from "nanoid";

import { db } from "@/lib/db";
import { member, organization } from "@/lib/db/schema";

type NewUserInput = {
  id: string;
  email: string;
  name: string;
};

/* Idempotent: returns existing org if the user already has one (owner).
   Creates a Personal Org + an owner membership otherwise. Used by:
   - lib/auth.ts databaseHooks.user.create.after  (new signups)
   - scripts/backfill-orgs.ts                     (existing users without org)

   Phase 1 idempotence assumption: a user has at most ONE membership (their
   own Personal Org), so `existing[0]` is unambiguous. When invitations land
   (Phase 4), this check must change to: find the membership where the org
   was created by this user — e.g. add a `kind: "personal" | "team"` column
   on `organization`, or look up via `member.role === "owner" AND org.kind === "personal"`. */
export async function createPersonalOrg(input: NewUserInput): Promise<{ orgId: string }> {
  // Idempotence: already a member somewhere?
  const existing = await db.select().from(member).where(eq(member.userId, input.id)).limit(1);
  if (existing.length > 0) {
    return { orgId: existing[0]!.organizationId };
  }

  const orgId = nanoid();
  const slug = `personal-${nanoid(10).toLowerCase()}`;
  const orgName = `Personal — ${input.email}`;

  await db.transaction(async (tx) => {
    await tx.insert(organization).values({
      id: orgId,
      name: orgName,
      slug,
      logo: null,
      metadata: null,
    });
    await tx.insert(member).values({
      id: nanoid(),
      organizationId: orgId,
      userId: input.id,
      role: "owner",
    });
  });

  return { orgId };
}
