import "server-only";

import { cookies } from "next/headers";
import { Query } from "node-appwrite";

import { createSessionClient } from "./server";
import { ACTIVE_TENANT_COOKIE } from "./tenant-types";
import { DATABASE_ID, TABLES } from "./schema";

export async function getUserTeams() {
  try {
    const { teams, tablesDB } = await createSessionClient();
    const allTeams = await teams.list();

    if (allTeams.teams.length === 0) return allTeams;

    // Filter to only teams that belong to this app (have a tenant_settings row in this database)
    const teamIds = allTeams.teams.map((t) => t.$id);
    const settings = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.tenantSettings,
      queries: [Query.equal("tenantId", teamIds), Query.limit(100)],
    });
    const validIds = new Set(settings.rows.map((r) => r.tenantId as string));

    const filtered = allTeams.teams.filter((t) => validIds.has(t.$id));
    return { ...allTeams, teams: filtered, total: filtered.length };
  } catch {
    return null;
  }
}

export async function getCrossAppTeams(): Promise<Array<{ $id: string; name: string }>> {
  try {
    const { teams, tablesDB } = await createSessionClient();
    const allTeams = await teams.list();

    if (allTeams.teams.length === 0) return [];

    const teamIds = allTeams.teams.map((t) => t.$id);
    const settings = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.tenantSettings,
      queries: [Query.equal("tenantId", teamIds), Query.limit(100)],
    });
    const thisAppIds = new Set(settings.rows.map((r) => r.tenantId as string));

    return allTeams.teams
      .filter((t) => !thisAppIds.has(t.$id))
      .map((t) => ({ $id: t.$id, name: t.name }));
  } catch {
    return [];
  }
}

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;
}
