/**
 * A connector's logo (SCRUM-601): which files fleet.admin accepts, and where the logo is read from.
 * Kept free of path aliases and framework imports so `npm test` runs it with Node alone.
 */

/** The API's limit too (UploadIntegrationLogoRequest): 5 MB. */
export const LOGO_MAX_BYTES = 5 * 1024 * 1024;

/** For the file picker: PNG, SVG, JPEG. */
export const LOGO_ACCEPT = ".png,.svg,.jpg,.jpeg,image/png,image/svg+xml,image/jpeg";

const ACCEPTED_TYPES = ["image/png", "image/svg+xml", "image/jpeg", "image/pjpeg"];
const ACCEPTED_EXTENSIONS = ["png", "svg", "jpg", "jpeg"];

export type LogoFileProblem = "type" | "size" | "empty";

/**
 * Checks a chosen file before it is sent: its type (from the browser's type, or its extension when the browser gives
 * none, which happens for some SVG files) and its size. The API checks the content again.
 */
export function checkLogoFile(file: { name: string; type: string; size: number }): LogoFileProblem | null {
  const extension = file.name.includes(".") ? file.name.split(".").pop()!.toLowerCase() : "";
  const type = file.type.toLowerCase();
  const typeOk = type ? ACCEPTED_TYPES.includes(type) : ACCEPTED_EXTENSIONS.includes(extension);

  if (!typeOk || !ACCEPTED_EXTENSIONS.includes(extension)) return "type";
  if (file.size === 0) return "empty";
  if (file.size > LOGO_MAX_BYTES) return "size";
  return null;
}

/**
 * The address to show a connector's logo: the full address the API gives (`logo_url`), else the stored path on the
 * API's origin (an API older than SCRUM-601), else null (the connector shows its placeholder).
 */
export function integrationLogoSrc(
  integration: { logo?: string | null; logo_url?: string | null } | null | undefined,
  backendOrigin: string
): string | null {
  if (!integration) return null;
  if (integration.logo_url) return integration.logo_url;
  if (!integration.logo) return null;
  if (/^https?:\/\//i.test(integration.logo)) return integration.logo;
  return `${backendOrigin.replace(/\/$/, "")}/${integration.logo.replace(/^\//, "")}`;
}
