import { getApplicationEvidence } from './applicationEvidenceApi';
import { fileStore } from './draftStorage';
import type { FileHandle, ServerEvidenceKind } from './types';
import { fetchWithTimeout, isAbortError, FETCH_EVIDENCE_DEADLINE_MS } from '../lib/networkTimeout';

export async function putFile(
  draftId: string,
  field: string,
  file: File | null,
): Promise<FileHandle | null> {
  const key = `${draftId}:${field}`;
  if (!file) {
    await fileStore.del(key);
    return null;
  }
  try {
    await fileStore.put(key, file);
  } catch (e) {
    console.error('IndexedDB put failed', e);
    throw e;
  }
  return {
    key,
    name: file.name,
    size: file.size,
    type: file.type,
    lastModified: file.lastModified,
  };
}

export type GetFileOptions = {
  caseId?: string | null;
  /** When handle.serverKind is missing, supply the field’s evidence kind (2.1 / 2.2). */
  serverKind?: ServerEvidenceKind;
};

export async function getFile(
  handle: FileHandle | null,
  options?: GetFileOptions,
): Promise<File | null> {
  if (!handle) return null;
  const blob = await fileStore.get(handle.key);
  if (blob) {
    return new File([blob], handle.name, { type: handle.type, lastModified: handle.lastModified });
  }
  const cid = options?.caseId;
  const sk = handle.serverKind ?? options?.serverKind;
  if (cid && sk) {
    try {
      const ev = await getApplicationEvidence(cid);
      const item =
        sk === 'research' ? ev.research : sk === 'textbook' ? ev.textbook : sk === 'technical' ? ev.technical : null;
      const url = item?.downloadUrl;
      if (url) {
        const r = await fetchWithTimeout(url, {}, FETCH_EVIDENCE_DEADLINE_MS);
        if (!r.ok) return null;
        const b = await r.blob();
        return new File([b], handle.name || item?.originalName || 'evidence.pdf', {
          type: handle.type || 'application/pdf',
          lastModified: handle.lastModified || Date.now(),
        });
      }
    } catch (e) {
      if (isAbortError(e)) {
        throw new Error(
          `Tải file minh chứng quá lâu (hết thời gian chờ ${Math.round(FETCH_EVIDENCE_DEADLINE_MS / 1000)} giây). Kiểm tra mạng rồi thử gửi lại.`,
        );
      }
      console.error('Evidence download (getFile) failed', e);
    }
  }
  return null;
}
