import type { ApplicationItem } from "@/data/mockApplications";
import type { AxiosRequestConfig } from "axios";

/** Reject 4xx/5xx so callers do not treat FastAPI `{ detail }` JSON as a successful entity body. */
export const axiosSuccessStatusOnly: AxiosRequestConfig = {
  validateStatus: (status: number) => status >= 200 && status < 300,
};

export function getNestedData<T>(raw: unknown): T {
  if (raw && typeof raw === "object" && "data" in raw && (raw as { data: unknown }).data !== undefined) {
    return (raw as { data: T }).data;
  }
  return raw as T;
}

/** Map API `draft_case_id` → `draftCaseId` for Postgres draft load on dashboard. */
export function normalizeApplicationItem(
  item: ApplicationItem & {
    draft_case_id?: string;
    du_va_dung?: string | null;
    nhan_xet?: string | null;
    initiative_classification?: ApplicationItem["initiativeClassification"];
    research_evidence_kind?: ApplicationItem["researchEvidenceKind"];
    textbook_evidence_kind?: ApplicationItem["textbookEvidenceKind"];
  },
): ApplicationItem {
  const fromSnake = typeof item.draft_case_id === "string" ? item.draft_case_id.trim() : "";
  const fromCamel = item.draftCaseId?.trim() ?? "";
  const draftCaseId = fromCamel || fromSnake || undefined;
  const duVaDung = item.duVaDung ?? item.du_va_dung ?? undefined;
  const nhanXet = item.nhanXet ?? item.nhan_xet ?? undefined;
  const initiativeClassification =
    item.initiativeClassification ?? item.initiative_classification ?? undefined;
  const researchEvidenceKind = item.researchEvidenceKind ?? item.research_evidence_kind ?? undefined;
  const textbookEvidenceKind = item.textbookEvidenceKind ?? item.textbook_evidence_kind ?? undefined;
  return {
    ...item,
    draftCaseId,
    duVaDung,
    nhanXet,
    initiativeClassification,
    researchEvidenceKind,
    textbookEvidenceKind,
  };
}
