/**
 * Case files API — browse & read every content subfolder of a case on disk.
 *
 * Surfaces the agent-produced work files (drafts, OCR text, research, originals…)
 * that previously lived only on the server filesystem. Backed by the pre-existing
 * `/local-files` endpoints, generalized to all subfolders (path-safe on the
 * server via `_resolve_case_file`).
 */

import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "./client";

export type CaseFile = {
  filename: string;
  size: number;
  /** Unix epoch seconds (float) of last modification. */
  modified_at: number;
};

export type CaseFileFolder = {
  /** Opaque folder key for the read endpoint (e.g. "documents__research"). */
  key: string;
  /** Leaf folder name (e.g. "research"). */
  name: string;
  /** Case-relative path (e.g. "documents/research"). */
  path: string;
  files: CaseFile[];
};

export type CaseFilesResponse = { folders: CaseFileFolder[] };

export function useCaseFiles(caseNumber: string | undefined) {
  return useQuery({
    queryKey: ["case-files", caseNumber ?? ""],
    queryFn: () =>
      apiRequest<CaseFilesResponse>(`/api/cases/${caseNumber}/local-files`),
    enabled: !!caseNumber,
  });
}

/** Direct URL to a single file — use as an <a href> for download/open. */
export function caseFileUrl(
  caseNumber: string,
  folderKey: string,
  filename: string,
): string {
  return `/api/cases/${encodeURIComponent(caseNumber)}/local-files/${encodeURIComponent(folderKey)}/${encodeURIComponent(filename)}`;
}

/** Fetch a text file's contents (md/txt/json) for the inline viewer. */
export function useCaseFileText(
  caseNumber: string | undefined,
  folderKey: string | undefined,
  filename: string | undefined,
) {
  return useQuery({
    queryKey: ["case-file-text", caseNumber ?? "", folderKey ?? "", filename ?? ""],
    queryFn: async () => {
      const res = await fetch(caseFileUrl(caseNumber!, folderKey!, filename!));
      if (!res.ok) throw new Error(`שגיאה בטעינת הקובץ (${res.status})`);
      return res.text();
    },
    enabled: !!caseNumber && !!folderKey && !!filename,
    staleTime: 30_000,
  });
}
