"use server";

import { cookies } from "next/headers";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { requireUser } from "@/lib/auth";
import { ORG_COOKIE } from "@/lib/org";
import { logoutAction } from "@/app/(auth)/actions";

/** Switch the active organization for the console (validated against membership). */
export async function switchOrgAction(orgId: string) {
  const user = await requireUser();
  const member = await db.orgMember.findFirst({ where: { orgId, userId: user.id } });
  if (!member && user.platformRole !== "SUPER_ADMIN") return;
  const jar = await cookies();
  jar.set(ORG_COOKIE, orgId, { httpOnly: true, sameSite: "lax", path: "/" });
  revalidatePath("/dashboard");
}

export async function consoleLogoutAction() {
  await logoutAction();
}
