import { fireEvent, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { jsonResponse, renderUi } from '../test/utils';
import { TelegramCard, type TelegramState } from './TelegramCard';
const urlOf = (input: RequestInfo | URL) => (typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
function backend(chats: { chat_id: string; title: string; type: string }[]) {
const calls: { method: string; url: string; body?: unknown }[] = [];
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const u = urlOf(input);
const method = (init?.method ?? 'GET').toUpperCase();
calls.push({ method, url: u, body: init?.body ? JSON.parse(String(init.body)) : undefined });
if (u.endsWith('/api/notifications/telegram/discover')) return jsonResponse({ chats });
if (u.endsWith('/api/notifications/telegram/chat')) return jsonResponse({ ok: true });
return jsonResponse({});
});
return calls;
}
describe('Telegram setup', () => {
afterEach(() => vi.restoreAllMocks());
it('without a bot token it shows the BotFather step and nothing else', () => {
renderUi();
expect(screen.getByTestId('tg-token-step')).toHaveTextContent('FPT_TELEGRAM_BOT_TOKEN');
expect(screen.queryByTestId('tg-discover')).not.toBeInTheDocument();
});
it('finds the chats that wrote to the bot and uses the chosen one', async () => {
const calls = backend([{ chat_id: '42', title: 'Sai', type: 'private' }]);
renderUi();
fireEvent.click(screen.getByTestId('tg-discover'));
fireEvent.click(await screen.findByRole('button', { name: 'Use this chat: Sai' }));
await waitFor(() => expect(calls.some((c) => c.method === 'POST' && c.url.endsWith('/api/notifications/telegram/chat'))).toBe(true));
expect(calls.find((c) => c.url.endsWith('/telegram/chat'))?.body).toEqual({ chat_id: '42', title: 'Sai' });
});
it('says so when nobody has written to the bot yet', async () => {
backend([]);
renderUi();
fireEvent.click(screen.getByTestId('tg-discover'));
expect(await screen.findByTestId('tg-none')).toHaveTextContent('send /start to your bot');
});
it('when connected it names the chat and offers a test message', () => {
const tg: TelegramState = { token_set: true, chat: { chat_id: '42', title: 'Sai' }, last_delivery: { at: '2026-11-05T10:00:00Z', ok: true, status: 200, error: null } };
renderUi();
expect(screen.getByTestId('tg-chat')).toHaveTextContent('Messages go to Sai');
expect(screen.getByTestId('tg-test')).toBeInTheDocument();
expect(screen.getByTestId('tg-last')).toHaveTextContent('Delivered');
});
});