import { openOcrTextInNewTab } from '../utils/ocr';
import type {
  EnsureAssetUrl,
  EnsurePreviewData,
  GetDocumentAsset,
} from '../utils/ocr';
import type { Document } from '../types/documents';

export type { Document };

const asyncFalse = async () => false;

const resolveDocumentDownloadHref = (document?: Document | null): string | null => {
  if (!document) {
    return null;
  }
  const downloadUrl = (document.current_version as { download?: { url: string } | null } | null)?.download?.url;
  if (!downloadUrl) {
    return null;
  }
  return downloadUrl;
};

const hasDocumentOcrAsset = (document?: Document | null, getDocumentAsset?: GetDocumentAsset | null): boolean => {
  if (!document || !getDocumentAsset) {
    return false;
  }
  return Boolean(getDocumentAsset(document, 'ocr-text'));
};

interface CreateDocumentActionStateArgs {
  document: Document | null;
  ensurePreviewData: EnsurePreviewData;
  ensureAssetUrl: EnsureAssetUrl;
  getDocumentAsset?: GetDocumentAsset | null;
  notifyApiError?: (error: unknown, message: string) => void;
  ocrErrorMessage?: string;
}

export const createDocumentActionState = ({
  document,
  ensurePreviewData,
  ensureAssetUrl,
  getDocumentAsset,
  notifyApiError,
  ocrErrorMessage = 'Unable to open OCR text.',
}: CreateDocumentActionStateArgs) => {
  if (!document) {
    return {
      downloadHref: null,
      hasOcr: false,
      openOcr: asyncFalse,
    };
  }

  const downloadHref = resolveDocumentDownloadHref(document);
  const hasOcr = hasDocumentOcrAsset(document, getDocumentAsset);

  const openOcr = hasOcr
    ? async () => {
      try {
        const success = await openOcrTextInNewTab({
          document,
          ensurePreviewData,
          getDocumentAsset,
          ensureAssetUrl,
        });
        if (!success) {
          notifyApiError?.(new Error('OCR text URL unavailable.'), ocrErrorMessage);
        }
        return success;
      } catch (error) {
        notifyApiError?.(error, ocrErrorMessage);
        throw error;
      }
    }
    : asyncFalse;

  return {
    downloadHref,
    hasOcr,
    openOcr,
  };
};

export const documentActionsTestExports = {
  resolveDocumentDownloadHref,
  hasDocumentOcrAsset,
};
