import {
  createDirectus,
  rest,
  authentication,
  DirectusClient,
  RestClient,
  AuthenticationClient,
} from "@directus/sdk";

export type MintelDirectusClient<Schema extends object = any> =
  DirectusClient<Schema> & RestClient<Schema> & AuthenticationClient<Schema>;

/**
 * Creates a Directus client configured with Mintel standards.
 * Automatically handles internal vs. external URLs based on environment.
 */
export function createMintelDirectusClient<Schema extends object = any>(
  url?: string,
): MintelDirectusClient<Schema> {
  const isServer = typeof window === "undefined";

  // 1. If an explicit URL is provided, use it.
  if (url) {
    return createDirectus<Schema>(url).with(rest()).with(authentication());
  }

  // 2. On server: Prioritize INTERNAL_DIRECTUS_URL, fallback to DIRECTUS_URL
  if (isServer) {
    const directusUrl =
      process.env.INTERNAL_DIRECTUS_URL ||
      process.env.DIRECTUS_URL ||
      "http://localhost:8055";
    return createDirectus<Schema>(directusUrl)
      .with(rest())
      .with(authentication());
  }

  // 3. In browser: Use a proxy path if we are on a different origin,
  // or use the current origin if no DIRECTUS_URL is set.
  const proxyPath = "/api/directus"; // Standard Mintel proxy path
  const browserUrl =
    typeof window !== "undefined"
      ? `${window.location.origin}${proxyPath}`
      : proxyPath;

  return createDirectus<Schema>(browserUrl).with(rest()).with(authentication());
}

/**
 * Ensures the client is authenticated using either a static token or admin credentials
 */
export async function ensureDirectusAuthenticated(
  client: MintelDirectusClient,
) {
  const token = process.env.DIRECTUS_API_TOKEN || process.env.DIRECTUS_TOKEN;
  const email = process.env.DIRECTUS_ADMIN_EMAIL;
  const password = process.env.DIRECTUS_ADMIN_PASSWORD;

  if (token) {
    client.setToken(token);
    return;
  }

  if (email && password) {
    try {
      await client.login({ email, password });
    } catch (e) {
      console.error("Failed to authenticate with Directus:", e);
      throw e;
    }
  }
}
