// src/lib/org/active-org-action.ts — persist the user's chosen active org.
"use server";
import { and, eq } from "drizzle-orm";
import { getActiveUserId } from "@/lib/active-org";
import { isImpersonating } from "@/lib/auth/impersonation-guard";
import { member, user } from "@/lib/db/auth-schema";
import { db } from "@/lib/db/client";

/**
 * Persist the org the user just switched to, so the next login restores it
 * (the session-create hook reads user.lastActiveOrgId). Fail-closed: the user
 * must be a member of the org. Call ALONGSIDE authClient.organization.setActive
 * (which updates the current session); this makes the choice durable.
 */
export async function persistActiveOrgAction(
  organizationId: string,
): Promise<void> {
  const userId = await getActiveUserId();
  const [m] = await db
    .select({ id: member.id })
    .from(member)
    .where(
      and(eq(member.userId, userId), eq(member.organizationId, organizationId)),
    )
    .limit(1);
  if (!m) throw new Error("Not a member of this organization");
  // En impersonation `userId` EST la cible : persister lastActiveOrgId
  // changerait son organisation par défaut à tous ses prochains logins. Le
  // switch de session (authClient.organization.setActive, côté navigateur de
  // l'opérateur) reste effectif ; seule la durabilité saute.
  if (await isImpersonating()) return;
  await db
    .update(user)
    .set({ lastActiveOrgId: organizationId })
    .where(eq(user.id, userId));
}
