import { describe, expect, it, vi } from "vitest";
import { processProductImages } from "./process-product-images";

describe("processProductImages", () => {
  it("processa URLs válidas e persiste imagens", async () => {
    const upload = vi.fn(async (url: string) => `https://storage.local/${encodeURIComponent(url)}`);
    const insert = vi.fn(async () => ({ error: null }));
    const updateProduct = vi.fn(async () => ({ error: null }));

    const result = await processProductImages({
      rowNumber: 3,
      imageUrls: ["https://example.com/a.jpg", "https://example.com/b.png"],
      tenantId: "tenant-1",
      productId: "product-1",
      upload,
      persist: { insert, updateProduct },
    });

    expect(result.imagesCreated).toBe(2);
    expect(result.errors).toHaveLength(0);
    expect(upload).toHaveBeenCalledTimes(2);
    expect(insert).toHaveBeenCalledTimes(1);
    expect(updateProduct).toHaveBeenCalledTimes(1);
  });

  it("ignora URLs inválidas e não persiste", async () => {
    const upload = vi.fn(async (url: string) => `https://storage.local/${encodeURIComponent(url)}`);
    const insert = vi.fn(async () => ({ error: null }));
    const updateProduct = vi.fn(async () => ({ error: null }));

    const result = await processProductImages({
      rowNumber: 5,
      imageUrls: ["nota-url", "ftp://example.com/a.jpg"],
      tenantId: "tenant-1",
      productId: "product-2",
      upload,
      persist: { insert, updateProduct },
    });

    expect(result.imagesCreated).toBe(0);
    expect(result.errors).toHaveLength(2);
    expect(upload).not.toHaveBeenCalled();
    expect(insert).not.toHaveBeenCalled();
    expect(updateProduct).not.toHaveBeenCalled();
  });

  it("continua quando upload falha", async () => {
    const upload = vi.fn(async (url: string) => {
      if (url.includes("bad")) throw new Error("Falha ao baixar");
      return `https://storage.local/${encodeURIComponent(url)}`;
    });
    const insert = vi.fn(async () => ({ error: null }));
    const updateProduct = vi.fn(async () => ({ error: null }));

    const result = await processProductImages({
      rowNumber: 7,
      imageUrls: ["https://example.com/bad.jpg", "https://example.com/good.jpg"],
      tenantId: "tenant-1",
      productId: "product-3",
      upload,
      persist: { insert, updateProduct },
    });

    expect(result.imagesCreated).toBe(1);
    expect(result.errors).toHaveLength(1);
    expect(upload).toHaveBeenCalledTimes(2);
    expect(insert).toHaveBeenCalledTimes(1);
    expect(updateProduct).toHaveBeenCalledTimes(1);
  });
});
