import { test, expect } from '@playwright/test';
import { BASE_URL, USER, ADMIN, loginAs } from '../helpers';

const WEBHOOK_SECRET = 'test-webhook-secret';

test.describe('Chat widget', () => {

    test('is visible on the site for a logged-in player', async ({ page }) => {
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/`);
        await expect(page.locator('[data-testid="chat-widget-toggle"]')).toBeVisible();
    });

    test('is not visible on WFBO admin pages', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo`);
        await expect(page.locator('[data-testid="chat-widget-toggle"]')).toHaveCount(0);
    });

    test('player can send a message and see a CSR reply arrive', async ({ page, request }) => {
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/`);

        await page.click('[data-testid="chat-widget-toggle"]');
        await page.fill('[data-testid="chat-input"]', 'Hello, I need help with my deposit.');
        await page.click('[data-testid="chat-send-button"]');

        // Player's own message appears immediately (pure DB round-trip, no Telegram involved).
        const ownMessage = page.locator('[data-testid="chat-message"][data-sender="player"]', {
            hasText: 'Hello, I need help with my deposit.',
        });
        await expect(ownMessage).toBeVisible();

        // Read the conversation id the send endpoint returned, exposed on the widget root.
        const conversationId = await page.locator('[data-testid="chat-widget"]').getAttribute('data-conversation-id');
        expect(conversationId).toBeTruthy();

        // Simulate Telegram delivering a CSR reply: POST directly to the real webhook
        // endpoint with the fixed test-env secret. No bot token is configured in the
        // test env, so the conversation's Telegram topic id falls back to its own DB
        // id (see ChatService::createConversation) — this is what message_thread_id
        // must match for the webhook to route the reply to the right conversation.
        const webhookResponse = await request.post(`${BASE_URL}/webhook/telegram`, {
            headers: { 'X-Telegram-Bot-Api-Secret-Token': WEBHOOK_SECRET },
            data: {
                message: {
                    text: 'Hi! Let me check that for you.',
                    message_thread_id: Number(conversationId),
                    message_id: 1,
                    from: { username: 'test_csr' },
                },
            },
        });
        expect(webhookResponse.ok()).toBeTruthy();

        const csrMessage = page.locator('[data-testid="chat-message"][data-sender="csr"]', {
            hasText: 'Hi! Let me check that for you.',
        });
        await expect(csrMessage).toBeVisible({ timeout: 15000 });
    });
});
