import "server-only";

import { cookies } from "next/headers";

import { createSessionClient } from "./server";
import { ACTIVE_TENANT_COOKIE } from "./tenant-types";

export async function getUserTeams() {
  try {
    const { teams } = await createSessionClient();
    return await teams.list();
  } catch {
    return null;
  }
}

export async function getActiveTenantId(): Promise<string | null> {
  const cookie = (await cookies()).get(ACTIVE_TENANT_COOKIE)?.value;
  if (cookie) return cookie;

  try {
    const { account } = await createSessionClient();
    const user = await account.get();
    const fromPrefs = (user.prefs as Record<string, unknown> | undefined)?.activeTenant;
    if (typeof fromPrefs === "string" && fromPrefs.length > 0) return fromPrefs;
  } catch {
    return null;
  }

  return null;
}
