import { Page, TestInfo } from '@playwright/test';

export async function attachGeoLocation(page: Page, testInfo: TestInfo) {
    try {
        // Thử với timeout ngắn hơn và retry
        const geoResponse = await page.request.get('https://ip-api.com/json/', {
            timeout: 10000, // 10s
            failOnStatusCode: false
        });

        if (geoResponse.ok()) {
            const geo = await geoResponse.json();
            await testInfo.attach('geo-location.json', {
                body: JSON.stringify(geo, null, 2),
                contentType: 'application/json'
            });
        } else {
            // Fallback: lưu lỗi thay vì crash
            await testInfo.attach('geo-location-error.txt', {
                body: `Failed: ${geoResponse.status()} - ${geoResponse.statusText()}`,
                contentType: 'text/plain'
            });
        }
    } catch (error) {
        // Không crash test nếu geo fail
        await testInfo.attach('geo-location-error.txt', {
            body: `Error: ${error}`,
            contentType: 'text/plain'
        });
    }
}

export async function captureAllRequests(page: Page, testInfo: TestInfo) {
    const xRequestIds: Array<{
        url: string;
        xRequestId: string;
        timestamp: string;
    }> = [];

    // Bắt x-request-id từ response
    page.on('response', async (response) => {
        try {
            const headers = await response.allHeaders();
            const xRequestId = headers['x-request-id'] || headers['x-requests-id'];
            
            if (xRequestId) {
                xRequestIds.push({
                    url: response.url(),
                    xRequestId: xRequestId,
                    timestamp: new Date().toISOString()
                });
            }
        } catch {
            // Ignore errors when page is closed
        }
    });

    // Trả về function để attach - gọi trong afterEach hoặc cuối test
    return {
        xRequestIds,
        attach: async () => {
            if (xRequestIds.length > 0) {
                await testInfo.attach('x-request-ids.json', {
                    body: JSON.stringify(xRequestIds, null, 2),
                    contentType: 'application/json'
                });
            }
        }
    };
}