import { isValidHttpUrl } from "@/lib/import-images";

export type ImagePersistence = {
  insert: (
    rows: { user_id: string; product_id: string; url: string; position: number }[]
  ) => Promise<{ error?: { message?: string } | null }>;
  updateProduct: (productId: string, url: string) => Promise<{ error?: { message?: string } | null }>;
};

export async function processProductImages(params: {
  rowNumber: number;
  imageUrls: string[];
  tenantId: string;
  productId: string;
  persist: ImagePersistence;
  upload: (url: string, tenantId: string, productId: string) => Promise<string>;
}) {
  const { rowNumber, imageUrls, tenantId, productId, persist, upload } = params;
  const errors: { rowNumber: number; message: string }[] = [];
  const cleanedUrls = imageUrls
    .filter((url) => typeof url === "string" && url.trim())
    .map((url) => String(url).trim());
  const uniqueUrls = Array.from(new Set(cleanedUrls));

  const uploadedUrls: string[] = [];
  for (const sourceUrl of uniqueUrls) {
    if (!isValidHttpUrl(sourceUrl)) {
      errors.push({ rowNumber, message: `Imagem inválida: ${sourceUrl}` });
      continue;
    }
    try {
      const publicUrl = await upload(sourceUrl, tenantId, productId);
      uploadedUrls.push(publicUrl);
    } catch (error) {
      const message = error instanceof Error ? error.message : "Falha ao importar imagem.";
      errors.push({ rowNumber, message: `${message} (${sourceUrl})` });
    }
  }

  if (!uploadedUrls.length) return { errors, imagesCreated: 0 };

  const imageRows = uploadedUrls.map((url, position) => ({
    user_id: tenantId,
    product_id: productId,
    url,
    position,
  }));
  const { error: imagesError } = await persist.insert(imageRows);
  if (imagesError) {
    errors.push({ rowNumber, message: imagesError.message || "Falha ao salvar imagens." });
    return { errors, imagesCreated: 0 };
  }

  const { error: updateError } = await persist.updateProduct(productId, uploadedUrls[0]);
  if (updateError) {
    errors.push({ rowNumber, message: updateError.message || "Falha ao salvar imagem principal." });
  }

  return { errors, imagesCreated: uploadedUrls.length };
}
