// Build a full public URL from the relative storage path returned by the API
const toStorageUrl = (path?: string | null): string | undefined => {
  if (!path) return undefined;
  if (path.startsWith("http")) return path; // already absolute
  const base = (process.env.NEXT_PUBLIC_BASE_URL || "https://api.weebard.com/").replace(/\/$/, "");
  return `${base}/storage/${path}`;
};

export function mapItemToCertificationFormValues(
  item: any,
): any {
  const yearVal = item.issue_year || item.passing_year || "";
  return {
    title: item.label || item.certificate_name,
    organization: item.organization || item.institution,
    issue_year: yearVal ? yearVal.toString() : "",
    credential_url: item.credential_url || item.url
      ? (item.credential_url || item.url).startsWith("http")
        ? item.credential_url || item.url
        : `https://${item.credential_url || item.url}`
      : "https://",
    // Pass the existing file URL so the edit dialog can show a preview
    certificate_file: toStorageUrl(item.certificate_file),
  };
}


export function mapFormToCertificationBody(
  cer: any,
  id?: string,
): any {
  const cleanUrl = (url?: string) => {
    if (!url || url === "https://") return "";
    return url.replace(/^https?:\/\//, "");
  };

  return {
    ...(id && { id }),
    certificate_name: cer.title,
    organization: cer.organization,
    issue_year: cer.issue_year?.value || cer.issue_year || "",
    credential_url: cleanUrl(cer.credential_url),
    // Pass the File object (or null) through — the API service handles FormData
    certificate_file: cer.certificate_file instanceof File ? cer.certificate_file : undefined,
  };
}
