export interface ProductImageItem {
  id: string;
  image_url: string;
  sort_order: number;
  is_primary: boolean;
}

function createFallbackId() {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}

export function normalizeProductImages(
  rawImages: unknown,
  fallbackImageUrl?: string | null
): ProductImageItem[] {
  const mapped = Array.isArray(rawImages)
    ? rawImages
        .map((image, index) => {
          if (!image || typeof image !== "object") return null;
          const row = image as Record<string, unknown>;
          const imageUrl = typeof row.image_url === "string" ? row.image_url.trim() : "";
          if (!imageUrl) return null;
          return {
            id: typeof row.id === "string" ? row.id : createFallbackId(),
            image_url: imageUrl,
            sort_order: typeof row.sort_order === "number" ? row.sort_order : index,
            is_primary: Boolean(row.is_primary),
          };
        })
        .filter((image): image is ProductImageItem => Boolean(image))
    : [];

  const sorted = mapped
    .slice()
    .sort((a, b) => a.sort_order - b.sort_order)
    .map((image, index) => ({ ...image, sort_order: index }));

  if (sorted.length === 0) {
    const fallback = typeof fallbackImageUrl === "string" ? fallbackImageUrl.trim() : "";
    if (!fallback) return [];
    return [
      {
        id: "legacy-main-image",
        image_url: fallback,
        sort_order: 0,
        is_primary: true,
      },
    ];
  }

  const hasPrimary = sorted.some((image) => image.is_primary);
  return sorted.map((image, index) => ({
    ...image,
    is_primary: hasPrimary ? image.is_primary : index === 0,
  }));
}

export function getPrimaryProductImageId(images: ProductImageItem[]) {
  if (!images.length) return null;
  return images.find((image) => image.is_primary)?.id || images[0].id;
}
