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

import { UnlockPrivateResponse } from "@/data/dto/chat";
import type { PendingChatPromotion } from "@/data/storage/navigation";
import {
  appendPromotionMessage,
  applyPromotionUnlockOutput,
  createChatPromotionState,
} from "@/stores/chat/helper/promotion";

const promotion: PendingChatPromotion = {
  promotionType: "image",
  lockType: "image_paywall",
  clientLockId: "promotion-1",
  createdAt: 1,
};

describe("chat promotion", () => {
  it("creates the requested locked message and appends it at the tail", () => {
    const state = createChatPromotionState(promotion);
    const messages = appendPromotionMessage(
      [
        {
          id: "history-1",
          content: "History",
          isFromAI: true,
          date: "2026-07-13",
        },
      ],
      state,
    );

    expect(messages.map((message) => message.id)).toEqual([
      "history-1",
      "promotion:promotion-1",
    ]);
    expect(messages[1]).toMatchObject({
      locked: true,
      lockReason: "image_paywall",
      imagePaywalled: true,
    });
  });

  it("replaces a temporary promotion with the real unlocked image", () => {
    const state = createChatPromotionState(promotion);
    const next = applyPromotionUnlockOutput(state, {
      displayMessageId: "promotion:promotion-1",
      request: {
        displayMessageId: "promotion:promotion-1",
        lockType: "image_paywall",
        clientLockId: "promotion-1",
      },
      response: UnlockPrivateResponse.from({
        unlocked: true,
        messageId: "backend-1",
        image: {
          type: "promotion",
          url: "https://example.com/unlocked.jpg",
        },
      }),
    });

    expect(next?.message).toMatchObject({
      id: "backend-1",
      imageUrl: "https://example.com/unlocked.jpg",
      imagePaywalled: false,
      locked: false,
    });
  });

  it("keeps the promotion last and removes matching history duplicates", () => {
    const state = createChatPromotionState(promotion, "backend-1");
    const messages = appendPromotionMessage(
      [
        {
          id: "backend-1",
          content: "Stale history copy",
          isFromAI: true,
          date: "2026-07-13",
        },
      ],
      state,
    );

    expect(messages).toEqual([state.message]);
  });
});
