import { afterEach, describe, expect, it, vi } from 'vitest';
import api from '../../api';
import { aiChatApi } from './api';

describe('AI chat API adapter', () => {
  afterEach(() => vi.restoreAllMocks());

  it('unwraps the backend success/data response', async () => {
    vi.spyOn(api, 'get').mockResolvedValue({
      success: true,
      data: [
        {
          id: 1,
          title: '会话',
          lockedSkillKey: null,
          createdAt: '2026-07-23T00:00:00.000Z',
          updatedAt: '2026-07-23T00:00:00.000Z',
          lastMessageAt: null,
        },
      ],
    });

    await expect(aiChatApi.listConversations()).resolves.toMatchObject([{ id: 1, title: '会话' }]);
  });

  it('loads every history page in chronological page order', async () => {
    vi.spyOn(api, 'get')
      .mockResolvedValueOnce({
        success: true,
        data: { items: [{ id: 1 }], total: 101, page: 1, limit: 100 },
      })
      .mockResolvedValueOnce({
        success: true,
        data: { items: [{ id: 101 }], total: 101, page: 2, limit: 100 },
      });

    const page = await aiChatApi.listMessages(3);
    expect(page.items.map((item) => item.id)).toEqual([1, 101]);
  });

  it('confirmReviewStep posts to the per-section confirm endpoint', async () => {
    const updated = {
      id: 'review-1',
      title: '批量导入',
      status: 'pending',
      sections: [
        { key: 'students', type: 'students', title: '学生', status: 'submitted' },
      ],
    };
    vi.spyOn(api, 'post').mockResolvedValue({ success: true, data: updated });

    await expect(aiChatApi.confirmReviewStep('review-1', 'students')).resolves.toEqual(updated);
    expect(api.post).toHaveBeenCalledWith(
      '/ai/chat/reviews/review-1/steps/students/confirm',
    );
  });

  it('confirmReviewGroup posts to the per-type confirm endpoint', async () => {
    const updated = {
      id: 'review-1',
      title: '批量导入',
      status: 'pending',
      sections: [
        { key: 'checkins_a', type: 'checkins', title: '入住A', status: 'submitted' },
      ],
    };
    vi.spyOn(api, 'post').mockResolvedValue({ success: true, data: updated });

    await expect(aiChatApi.confirmReviewGroup('review-1', 'checkins')).resolves.toEqual(updated);
    expect(api.post).toHaveBeenCalledWith(
      '/ai/chat/reviews/review-1/types/checkins/confirm',
    );
  });
});
