import { Clarizen, ClarizenApiError } from "@arco/clarizen-lib";

export function getApiKey(): string | undefined {
  return process.env.CLARIZEN_API_KEY ?? process.env.API_KEY_AW;
}

export function createClarizenClient(): Clarizen {
  const apiKey = getApiKey();
  if (!apiKey) {
    throw new Error(
      "Defina CLARIZEN_API_KEY ou API_KEY_AW no arquivo .env na raiz do projeto.",
    );
  }

  return new Clarizen({
    baseUrl: process.env.CLARIZEN_BASE_URL ?? "https://api.clarizen.com",
    apiToken: apiKey,
  });
}

export async function checkClarizenAuth(
  clarizen: Clarizen,
): Promise<
  { ok: true; userId: string } | { ok: false; message: string; status?: number }
> {
  try {
    const session = await clarizen.authentication.getSessionInfo();
    return { ok: true, userId: session.userId };
  } catch (err) {
    if (err instanceof ClarizenApiError) {
      return {
        ok: false,
        message: err.message,
        status: err.status === 401 || err.status === 403 ? err.status : 502,
      };
    }
    const message = err instanceof Error ? err.message : "Falha de autenticação";
    return { ok: false, message, status: 502 };
  }
}
