import type { AxiosRequestConfig } from "axios";
import { apiClient } from "@/shared/api/client";
import { env } from "@/shared/config/env";

/** Only treat 2xx as success so 401/403 from evidence API surface as errors (global client allows <500). */
const OK_ONLY: AxiosRequestConfig = {
  validateStatus: (status) => status >= 200 && status < 300,
};

export type ServerEvidenceKind = "research" | "textbook" | "technical";

export interface EvidenceUploadResponse {
  ok: boolean;
  caseId: string;
  kind: ServerEvidenceKind;
  storageKey: string;
  originalName: string | null;
  byteSize?: number;
  uploadedAt: string;
}

export interface EvidenceItemMeta {
  kind: ServerEvidenceKind;
  originalName: string | null;
  byteSize: number | null;
  mimeType?: string | null;
  uploadedAt: string | null;
  storageKey: string;
  /** Presigned GET with Content-Disposition: attachment (save / open in new tab). */
  downloadUrl: string | null;
  /** Presigned GET with Content-Disposition: inline — use for embedded PDF viewers. */
  viewUrl?: string | null;
  reviewStatus?: string | null;
  reviewedAt?: string | null;
}

export interface EvidenceBundle {
  research: EvidenceItemMeta | null;
  textbook: EvidenceItemMeta | null;
  technical: EvidenceItemMeta | null;
}

export async function uploadApplicationEvidence(
  caseId: string,
  kind: ServerEvidenceKind,
  file: File,
): Promise<EvidenceUploadResponse> {
  const fd = new FormData();
  fd.append("kind", kind);
  fd.append("file", file);
  return apiClient.post<EvidenceUploadResponse>(
    `/api/v1/application-drafts/${encodeURIComponent(caseId)}/evidence`,
    fd,
    OK_ONLY,
  );
}

export async function deleteApplicationEvidence(caseId: string, kind: ServerEvidenceKind): Promise<void> {
  await apiClient.delete(
    `/api/v1/application-drafts/${encodeURIComponent(caseId)}/evidence?kind=${encodeURIComponent(kind)}`,
    OK_ONLY,
  );
}

export async function getApplicationEvidence(caseId: string): Promise<EvidenceBundle> {
  return apiClient.get<EvidenceBundle>(
    `/api/v1/application-drafts/${encodeURIComponent(caseId)}/evidence`,
    OK_ONLY,
  );
}

/** Same-origin / HTTPS API path to stream evidence (avoids mixed-content iframes vs http://…:19000 presign). */
export function applicationDraftEvidenceContentUrl(
  caseId: string,
  kind: ServerEvidenceKind,
  opts?: { attachment?: boolean },
): string {
  const q = new URLSearchParams({ kind });
  if (opts?.attachment) q.set("attachment", "true");
  const path = `/api/v1/application-drafts/${encodeURIComponent(caseId)}/evidence/content?${q.toString()}`;
  const prefix = env.API_URL.replace(/\/$/, "");
  return prefix ? `${prefix}${path}` : path;
}

export async function patchEvidenceReview(
  caseId: string,
  kind: ServerEvidenceKind,
  decision: "approved" | "rejected",
): Promise<void> {
  await apiClient.patch(
    `/api/v1/application-drafts/${encodeURIComponent(caseId)}/evidence/review?kind=${encodeURIComponent(kind)}`,
    { decision },
    OK_ONLY,
  );
}
