import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { buildTicketEmailParams, sendTicketEmail } from "./emailjs";

describe("EmailJS ticket delivery", () => {
  beforeEach(() => vi.stubEnv("EMAILJS_PRIVATE_KEY", "test-private-key"));
  afterEach(() => {
    vi.unstubAllGlobals();
    vi.unstubAllEnvs();
  });

  it("maps issued ticket details to the configured template variables", () => {
    const params = buildTicketEmailParams({
      orderId: 42,
      attendeeName: "Ama Mensah",
      attendeeEmail: "ama@example.com",
      eventTitle: "Accra Design Night",
      eventStartsAt: new Date("2026-09-10T18:00:00.000Z"),
      eventLocation: "Osu, Accra",
      ticketType: "General admission",
      quantity: 2,
      qrTokens: ["gng_one", "gng_two"],
    });

    expect(params).toMatchObject({
      to_email: "ama@example.com",
      recipient: "ama@example.com",
      recipients: "ama@example.com",
      to_name: "Ama Mensah",
      event_title: "Accra Design Night",
      event_location: "Osu, Accra",
      ticket_type: "General admission",
      quantity: "2",
      order_id: "42",
      ticket_codes: "gng_one, gng_two",
      ticket_code: "gng_one",
    });
  });

  it("sends the mapped payload through EmailJS without exposing ticket creation to transport errors", async () => {
    const fetchMock = vi.fn().mockResolvedValue(new Response("OK", { status: 200 }));
    vi.stubGlobal("fetch", fetchMock);

    const sent = await sendTicketEmail({
      orderId: 42,
      attendeeName: "Ama Mensah",
      attendeeEmail: "ama@example.com",
      eventTitle: "Accra Design Night",
      eventStartsAt: new Date("2026-09-10T18:00:00.000Z"),
      eventLocation: "Osu, Accra",
      ticketType: "General admission",
      quantity: 1,
      qrTokens: ["gng_one"],
    });

    expect(sent).toBe(true);
    expect(fetchMock).toHaveBeenCalledWith(
      "https://api.emailjs.com/api/v1.0/email/send",
      expect.objectContaining({
        method: "POST",
        body: expect.stringContaining('"accessToken":"test-private-key"'),
      }),
    );
  });
});
