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) => {
        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()
            });
        }
    });

    // Attach danh sách x-request-id vào report khi test kết thúc
    page.context().on('close', async () => {
        await testInfo.attach('x-request-ids.json', {
            body: JSON.stringify(xRequestIds, null, 2),
            contentType: 'application/json'
        });
    });

    return xRequestIds;
}