import { apiDelete, apiDownloadFile, apiGet, apiPost, apiPostFormData } from "@/lib/api";

export type ImportErrorItem = {
  row: number | null;
  column: string | null;
  field: string | null;
  value: string | null;
  code: string;
  message: string;
  severity?: "error" | "warning";
};

export type ImportFieldChange = {
  field: string;
  label: string;
  old: string;
  new: string;
};

export type ImportPreviewRow = {
  row: number;
  values: Record<string, unknown>;
  errors: ImportErrorItem[];
  action?: "create" | "update";
  changes?: ImportFieldChange[];
};

export type ImportSessionPayload = {
  id: number;
  type: string;
  filename: string;
  status: string;
  total_rows: number;
  valid_rows: number;
  error_rows: number;
  created_rows: number;
  can_commit: boolean;
  errors: ImportErrorItem[];
  rows: ImportPreviewRow[];
  message?: string | null;
};

export type ImportColumn = {
  key: string;
  label: string;
  displayKey?: string;
};

export async function downloadImportTemplate(path: string, filename: string): Promise<void> {
  await apiDownloadFile(path, filename);
}

export async function uploadImportFile(path: string, file: File): Promise<ImportSessionPayload> {
  const formData = new FormData();
  formData.append("file", file);
  return apiPostFormData<ImportSessionPayload>(path, formData);
}

export async function fetchImportSession(path: string): Promise<ImportSessionPayload> {
  return apiGet<ImportSessionPayload>(path);
}

export async function commitImportSession(path: string): Promise<ImportSessionPayload> {
  return apiPost<ImportSessionPayload>(path, {});
}

export async function cancelImportSession(path: string): Promise<void> {
  await apiDelete(path);
}

export function displayCell(row: ImportPreviewRow, column: ImportColumn): string {
  const key = column.displayKey ?? column.key;
  const value = row.values[key] ?? row.values[column.key];
  if (value === null || value === undefined || value === "") return "—";
  if (typeof value === "boolean") return value ? "فعال" : "غیرفعال";
  return String(value);
}

export function rowBlockingErrors(row: ImportPreviewRow): ImportErrorItem[] {
  return row.errors.filter((item) => (item.severity ?? "error") !== "warning");
}

export function rowWarnings(row: ImportPreviewRow): ImportErrorItem[] {
  return row.errors.filter((item) => item.severity === "warning");
}

export function changeForColumn(row: ImportPreviewRow, column: ImportColumn): ImportFieldChange | null {
  return (row.changes ?? []).find((item) => item.field === column.key) ?? null;
}

export function changedFields(row: ImportPreviewRow): Set<string> {
  return new Set(
    (row.changes ?? [])
      .filter((item) => item.old !== item.new)
      .map((item) => item.field),
  );
}
