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

import { ChatWebSocket } from "../chat-websocket";

describe("ChatWebSocket payment guidance", () => {
  it("parses the same role-bound decision emitted by HTTP", () => {
    const socket = new ChatWebSocket("ws://example.test/chat", "token");
    const onPaymentGuidance = vi.fn();
    socket.onPaymentGuidance = onPaymentGuidance;

    receive(socket, {
      type: "payment_guidance",
      data: {
        guidanceId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
        characterId: "maya-tan",
        characterName: "Maya Tan",
        scene: "voiceLocked",
        mode: "guide",
        title: "Keep talking with Maya",
        copy: "Hey love, I want to keep talking with you.",
        ctaLabel: "View VIP & credit options",
        purchaseOptions: ["vip", "topup"],
        target: "subscription",
        ruleId: "payment_guidance_voiceLocked",
      },
    });

    expect(onPaymentGuidance).toHaveBeenCalledWith(
      expect.objectContaining({
        characterId: "maya-tan",
        scene: "voiceLocked",
      }),
    );
  });

  it("ignores malformed guidance instead of rendering the wrong role", () => {
    const socket = new ChatWebSocket("ws://example.test/chat", "token");
    const onPaymentGuidance = vi.fn();
    socket.onPaymentGuidance = onPaymentGuidance;

    receive(socket, {
      type: "payment_guidance",
      data: { characterId: "elio" },
    });

    expect(onPaymentGuidance).not.toHaveBeenCalled();
  });

  it("delivers a persisted commercial thank-you as a live role message", () => {
    const socket = new ChatWebSocket("ws://example.test/chat", "token");
    const onCommercialMessage = vi.fn();
    socket.onCommercialMessage = onCommercialMessage;

    receive(socket, {
      type: "commercial_message",
      messageId: "message-1",
      message: "Thank you for supporting me.",
      characterId: "maya-tan",
      createdAt: "2026-07-28T00:00:00.000Z",
    });

    expect(onCommercialMessage).toHaveBeenCalledWith({
      messageId: "message-1",
      message: "Thank you for supporting me.",
      characterId: "maya-tan",
      createdAt: "2026-07-28T00:00:00.000Z",
    });
  });
});

function receive(socket: ChatWebSocket, payload: unknown): void {
  (
    socket as unknown as { handleMessage: (data: string) => void }
  ).handleMessage(JSON.stringify(payload));
}
