// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { DownloadLightboxForm } from "./DownloadLightboxForm";
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn() }) }));
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
const photos = [
{ assetId: "first", albumId: "allowed", filename: "first.jpg" },
{ assetId: "second", albumId: "allowed", filename: "second.jpg" },
];
const options = {
priceCents: 1500,
collabEnabled: false,
priorUsagesByAsset: {
second: [{ id: "prior", purpose: "Früherer Artikel", createdAt: "2026-11-01T12:00:00Z" }],
},
};
test("books every photo as a new usage and offers a choice only for already downloaded ones", () => {
render();
fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" }));
expect(screen.queryByText("Bild auslassen")).toBeNull();
const [firstRow, secondRow] = screen.getAllByRole("listitem");
expect(within(firstRow).queryByText("Bereits genutzt")).toBeNull();
expect(within(secondRow).getByText("Bereits genutzt")).toBeTruthy();
const submit = screen.getByRole("button", { name: "Nutzungen bestätigen und laden" });
expect(submit.disabled).toBe(true);
fireEvent.change(screen.getByLabelText("Verwendungszweck"), { target: { value: "Neuer Artikel" } });
expect(submit.disabled).toBe(false);
expect(screen.getByRole("status").textContent).toMatch(/2 neue Nutzungen.*30,00/);
});
test("switching to 'Bereits genutzt' repeats the earlier usage and keeps keys after a failed request", async () => {
const fetch = vi.fn().mockRejectedValue(new Error("connection lost"));
vi.stubGlobal("fetch", fetch);
render();
fireEvent.click(screen.getByRole("button", { name: "ZIP-Download vorbereiten" }));
fireEvent.click(within(screen.getAllByRole("listitem")[1]).getByText("Bereits genutzt"));
fireEvent.change(screen.getByLabelText("Verwendungszweck"), { target: { value: "Neuer Artikel" } });
expect(screen.getByRole("status").textContent).toMatch(/1 neue Nutzung.*1 kostenlos erneut.*15,00/);
const submit = screen.getByRole("button", { name: "Nutzungen bestätigen und laden" });
fireEvent.click(submit);
await waitFor(() => expect(submit.disabled).toBe(false));
fireEvent.click(submit);
await waitFor(() => expect(submit.disabled).toBe(false));
const payload = JSON.parse(fetch.mock.calls[0][1].body);
expect(payload).toEqual({
maxPriceCents: 1500,
items: [
{ assetId: "first", albumId: "allowed", purpose: "Neuer Artikel", idempotencyKey: expect.any(String) },
{ assetId: "second", usageId: "prior", idempotencyKey: expect.any(String) },
],
});
expect(JSON.parse(fetch.mock.calls[1][1].body)).toEqual(payload);
});