const axios = require('axios');
const fs = require('fs');

async function test() {
    console.log('Testing two-step download...');
    const url = 'https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.40-winx64.zip';
    const landing = 'https://dev.mysql.com/downloads/mysql/';

    try {
        console.log('1. Fetching landing page for cookies...');
        const landingRes = await axios.get(landing, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
            }
        });

        const cookies = landingRes.headers['set-cookie'];
        console.log('Cookies received:', cookies ? cookies.length : 0);

        console.log('2. Downloading ZIP with cookies...');
        const downloadRes = await axios({
            url,
            method: 'GET',
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'Referer': landing,
                'Cookie': cookies ? cookies.join('; ') : ''
            },
            responseType: 'arraybuffer',
            timeout: 10000
        });

        console.log('Download Status:', downloadRes.status);
        console.log('Content Length:', downloadRes.data.length);
        if (downloadRes.data.length < 5000) {
            console.log('Content Preview:', downloadRes.data.toString().substring(0, 500));
        } else {
            console.log('Download SUCCESS (likely binary)');
        }
    } catch (e) {
        console.error('ERROR:', e.response ? e.response.status : e.message);
        if (e.response && e.response.data) {
            console.log('Error Data:', e.response.data.toString().substring(0, 200));
        }
    }
}

test();
