// First URL
// const url1 = "https://api.amemv.com/insights/lynx_web/anchor/preview?anchor_type=internet_service&app_id=1128&cmpt_version=1&component_id=7430558813054405430&download_style=1&interaction_style=1&is_preview=1&item_id=0&owner_id=1809047160845323&sec_uid=MS4wLjABAAAAHBDxS7uq2FpOE5kTjzuQTuIHOqL460dWJi9izIZedWIYRktaqewXWOw_rFvP8Avx";

async function fetchData(url1) {
    try {

        // Parse URL parameters using URLSearchParams
        const urlObj = new URL(url1);
        const params = Object.fromEntries(urlObj.searchParams);

        // Extract required parameters
        const component_id = params.component_id;
        const cmpt_version = params.cmpt_version;
        const item_id = params.item_id;
        const sec_uid = params.sec_uid;
        const app_id = params.app_id;
        // Construct extra parameter
        const extra_data = {
            item_id: item_id,
            author_id: params.owner_id,
            device_platform: 'ios'
        };

        // Construct parameters for second URL
        const params2 = new URLSearchParams({
            component_id: component_id,
            cmpt_version: cmpt_version,
            extra: JSON.stringify(extra_data),
            app_id: app_id,
            sec_uid: sec_uid
        });

        // Construct second URL
        const url2 = `https://api.amemv.com/aweme/v1/saiyan/industry/component/anchor/page/?${params2.toString()}`;

        const response = await fetch(url2, {
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const jsonData = await response.json();
        const anchorData = JSON.parse(jsonData.anchor_page.data);
        if (anchorData && anchorData.length > 0) {
            const item = anchorData[0];
            if(item.wechat_microapp_title==undefined||item.wechat_microapp_jump_url==undefined||item.wechat_microapp_jump_url.length<=0||item.wechat_microapp_title.length<=0){
                console.log("item:",item)
                return null
            }
            return {
                wechat_microapp_jump_url: item.wechat_microapp_jump_url || '',
                wechat_microapp_title: item.wechat_microapp_title || '',
                item:item
            };
        }
        return null;
    } catch (error) {
        console.error('Error:', error,url1);
        return null
    }
}

module.exports = {fetchData}