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

import { POST } from '../../src/app/api/threads/[threadId]/message/route';

const { mockAuthToken, mockFetchMutation, mockFetchQuery, mockProxyWorker } =
  vi.hoisted(() => ({
    mockAuthToken: vi.fn(),
    mockFetchMutation: vi.fn(),
    mockFetchQuery: vi.fn(),
    mockProxyWorker: vi.fn(),
  }));

vi.mock('@convex-dev/auth/nextjs/server', () => ({
  convexAuthNextjsToken: mockAuthToken,
}));

vi.mock('convex/nextjs', () => ({
  fetchMutation: mockFetchMutation,
  fetchQuery: mockFetchQuery,
}));

vi.mock('@/lib/agent-worker-proxy', () => ({
  proxyWorker: mockProxyWorker,
}));

describe('thread message route', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockAuthToken.mockResolvedValue('token');
  });

  it('returns 404 when the thread detail query returns null', async () => {
    mockFetchQuery.mockResolvedValue(null);

    const response = await POST(
      new Request('http://localhost/api/threads/thread-1/message', {
        method: 'POST',
        body: JSON.stringify({ content: 'Hello' }),
      }),
      { params: Promise.resolve({ threadId: 'thread-1' }) },
    );

    expect(response.status).toBe(404);
    await expect(response.json()).resolves.toEqual({
      error: 'Thread not found.',
    });
    expect(mockFetchMutation).not.toHaveBeenCalled();
    expect(mockProxyWorker).not.toHaveBeenCalled();
  });
});
