import { createDirectus, rest, authentication } from "@directus/sdk";
import { config } from "./config";
import { getServerAppServices } from "./services/create-services.server";

const { url, adminEmail, password, token, internalUrl } = config.directus;

// Use internal URL if on server to bypass Gatekeeper/Auth/Proxy issues
const effectiveUrl =
  typeof window === "undefined" && internalUrl ? internalUrl : url;

const client = createDirectus(effectiveUrl).with(rest()).with(authentication());

/**
 * Ensures the client is authenticated.
 * Falls back to login with admin credentials if no static token is provided.
 */
export async function ensureAuthenticated() {
  if (token) {
    client.setToken(token);
    return;
  }

  if (adminEmail && password) {
    try {
      await client.login({ email: adminEmail, password: password });
    } catch (e) {
      if (typeof window === "undefined") {
        getServerAppServices().errors.captureException(e, {
          phase: "directus_auth",
        });
      }
      console.error("Failed to authenticate with Directus login fallback:", e);
    }
  }
}

export default client;
