/* @vitest-environment jsdom */

import { beforeEach, describe, expect, it, vi } from "vitest";

const recordActionEventMock = vi.hoisted(() => vi.fn());

vi.mock("@/data/services/api", () => ({
  chatApi: { recordActionEvent: recordActionEventMock },
}));

import {
  readPendingChatActionArrival,
  recordChatActionEvent,
  rememberChatActionArrival,
} from "../chat_action_events";

const action = {
  actionId: "action-1",
  kind: "support" as const,
  type: "openFeedback" as const,
  copy: "Open feedback.",
  ctaLabel: "Open Feedback",
  ruleId: null,
  orderId: null,
};

describe("chat action events", () => {
  beforeEach(() => {
    window.sessionStorage.clear();
    recordActionEventMock.mockReset();
    recordActionEventMock.mockResolvedValue({});
  });

  it("reuses the event UUID when an event is safely retried", async () => {
    await recordChatActionEvent(action, "elio", "opened");
    await recordChatActionEvent(action, "elio", "opened");

    const first = recordActionEventMock.mock.calls[0]?.[0];
    const second = recordActionEventMock.mock.calls[1]?.[0];
    expect(first.eventId).toMatch(
      /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
    );
    expect(second.eventId).toBe(first.eventId);
  });

  it("tracks the intended destination instead of an external URL", () => {
    rememberChatActionArrival(
      action,
      "elio",
      "/feedback?returnTo=%2Fcharacters%2Felio%2Fchat",
    );
    expect(readPendingChatActionArrival()).toEqual({
      actionId: "action-1",
      characterId: "elio",
      expectedPath: "/feedback",
    });

    window.sessionStorage.clear();
    rememberChatActionArrival(action, "elio", "https://example.com/checkout");
    expect(readPendingChatActionArrival()).toBeNull();
  });
});
