import { formatDateTime } from '../utils/date';

interface DocumentVersionMetadata {
  checksum?: string | null;
}

interface DocumentMetadata {
  [key: string]: unknown;
}

export interface DocumentLike {
  created_at?: string | null;
  updated_at?: string | null;
  filename?: string | null;
  original_name?: string | null;
  content_type?: string | null;
  metadata?: DocumentMetadata | null;
  current_version?: DocumentVersionMetadata | null;
}

export interface DocumentMetadataItem {
  label: string;
  value: string | null | undefined;
}

export const buildDocumentMetadataItems = (document?: DocumentLike | null): DocumentMetadataItem[] => {
  if (!document) {
    return [];
  }

  const metadata = document.current_version || {};

  return [
    { label: 'Created at', value: formatDateTime(document.created_at) },
    { label: 'Updated at', value: formatDateTime(document.updated_at) },
    {
      label: 'Filename',
      value: document.filename,
    },
    {
      label: 'Original filename',
      value: document.original_name || '—',
    },
    {
      label: 'SHA-256 checksum',
      value: metadata.checksum || '—',
    },
    {
      label: 'Content type',
      value: document.content_type || '—',
    },
  ];
};

export const extractDocumentMetadataPayload = (document?: DocumentLike | null): DocumentMetadata | null => {
  if (!document?.metadata) {
    return null;
  }
  const keys = Object.keys(document.metadata);
  if (!keys.length) {
    return null;
  }
  return document.metadata;
};

export default buildDocumentMetadataItems;
