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

const repository = vi.hoisted(() => ({
  saveOpeningMessage: vi.fn(),
  getHistory: vi.fn(),
  saveMessagesToLocal: vi.fn(),
  prefetchMediaForMessages: vi.fn(),
}));

vi.mock("@/data/repositories/chat_repository_loader", () => ({
  loadChatRepository: vi.fn(async () => repository),
}));

import { syncNetworkHistory } from "@/stores/chat/chat-history-sync";

describe("chat opening-message history sync", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    repository.saveOpeningMessage.mockResolvedValue({
      success: true,
      data: {
        messageId: "opening-1",
        created: true,
        openingMessage: "Hello from Elio",
        createdAt: "2026-07-23T00:00:00Z",
      },
    });
    repository.getHistory.mockResolvedValue({
      success: true,
      data: {
        messages: [
          {
            id: "opening-1",
            role: "assistant",
            type: "text",
            content: "Hello from Elio",
            createdAt: "2026-07-23T00:00:00Z",
            audioUrl: null,
            image: { type: null, url: null },
            lockDetail: { locked: false, reason: null },
          },
        ],
        total: 1,
        limit: 50,
        offset: 0,
      },
    });
    repository.saveMessagesToLocal.mockResolvedValue({
      success: true,
      data: undefined,
    });
    repository.prefetchMediaForMessages.mockResolvedValue({
      success: true,
      data: undefined,
    });
  });

  it("persists the greeting before loading authoritative history", async () => {
    const output = await syncNetworkHistory(
      "elio",
      0,
      [],
      "user:test::character:elio",
      "Hello from Elio",
    );

    expect(repository.saveOpeningMessage).toHaveBeenCalledWith(
      "elio",
      "Hello from Elio",
      { signal: undefined },
    );
    expect(repository.saveOpeningMessage.mock.invocationCallOrder[0]).toBeLessThan(
      repository.getHistory.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER,
    );
    expect(output?.messages).toMatchObject([
      {
        remoteId: "opening-1",
        content: "Hello from Elio",
      },
    ]);
    expect(output?.messages[0]?.isSynthetic).toBeUndefined();
  });
});
