// 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}`;
};

// MappedAward (list item) → RHF default values for edit mode
export function mapItemToAwardFormValues(item: any): any {
  const yearVal = item.year || item.passing_year || "";
  return {
    title: item.label || item.award_name,
    organization: item.organization || item.institution,
    year: yearVal ? yearVal.toString() : "",
    award_url:
      item.award_url || item.url
        ? (item.award_url || item.url)?.startsWith("http")
          ? item.award_url || item.url
          : `https://${item.award_url || item.url}`
        : "https://",
    // Pass the existing file URL so the edit dialog can show a preview
    award_file: toStorageUrl(item.award_file),
  };
}

// RHF form values → API request body
export function mapFormToAwardBody(form: any, uuid?: string) {
  return {
    ...(uuid ? { uuid } : {}),
    award_name: form.title,
    organization: form.organization,
    year: form.year?.value ?? form.year, // ✅ unwrap {label, value} → string
    award_url: form.award_url || form.url || "", // ✅ normalize both fields
    // Pass the File object (or null) through — the API service handles FormData
    award_file: form.award_file instanceof File ? form.award_file : undefined,
  };
}
