import "server-only";

import { cookies } from "next/headers";
import {
  Account,
  Client,
  Databases,
  Storage,
  TablesDB,
  Teams,
  Users,
} from "node-appwrite";

const endpoint = process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT;
const projectId = process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID;
const apiKey = process.env.APPWRITE_API_KEY;

if (!endpoint || !projectId) {
  throw new Error(
    "Missing NEXT_PUBLIC_APPWRITE_ENDPOINT or NEXT_PUBLIC_APPWRITE_PROJECT_ID. Check .env.local.",
  );
}

export const APPWRITE_SESSION_COOKIE = "isletmem-session";

function baseClient() {
  return new Client().setEndpoint(endpoint!).setProject(projectId!);
}

export function createAdminClient() {
  if (!apiKey) {
    throw new Error("Missing APPWRITE_API_KEY. Required for admin operations.");
  }
  const client = baseClient().setKey(apiKey);
  return {
    client,
    account: new Account(client),
    teams: new Teams(client),
    users: new Users(client),
    databases: new Databases(client),
    tablesDB: new TablesDB(client),
    storage: new Storage(client),
  };
}

export async function createSessionClient() {
  const session = (await cookies()).get(APPWRITE_SESSION_COOKIE);
  if (!session?.value) {
    throw new Error("No active session.");
  }
  const client = baseClient().setSession(session.value);
  return {
    client,
    account: new Account(client),
    teams: new Teams(client),
    databases: new Databases(client),
    tablesDB: new TablesDB(client),
    storage: new Storage(client),
  };
}

export async function getCurrentUser() {
  try {
    const { account } = await createSessionClient();
    return await account.get();
  } catch {
    return null;
  }
}
