const logger = require('consola');
const { asyncHttpsGet } = require('../../utils/network');

const BaseUrl = 'https://music-dl.sayqz.com/api/';

function buildApiUrl(params = {}) {
    const searchParams = new URLSearchParams(params);
    return `${BaseUrl}?${searchParams.toString()}`;
}

async function fetchJson(params = {}) {
    const url = buildApiUrl(params);
    const raw = await asyncHttpsGet(url);
    if (!raw) {
        return null;
    }
    try {
        return JSON.parse(raw);
    } catch (err) {
        logger.error(`TuneHub 返回非 JSON: ${url}`);
        return null;
    }
}

async function getPlaylistDetail(source, playlistId) {
    const response = await fetchJson({
        source,
        id: playlistId,
        type: 'playlist',
    });
    if (!response || response.code !== 200 || !response.data) {
        return false;
    }
    return response.data;
}

async function getSongInfo(source, songId) {
    const response = await fetchJson({
        source,
        id: songId,
        type: 'info',
    });
    if (!response || response.code !== 200 || !response.data) {
        return false;
    }
    return response.data;
}

async function searchSongs(keyword, {
    source = '',
    limit = 20,
    aggregate = true,
} = {}) {
    const params = {
        keyword,
        limit,
    };
    if (aggregate) {
        params.type = 'aggregateSearch';
    } else {
        params.type = 'search';
        params.source = source;
    }
    const response = await fetchJson(params);
    if (!response || response.code !== 200 || !response.data) {
        return false;
    }
    return response.data;
}

function buildSongUrl(source, songId, br) {
    const params = {
        source,
        id: songId,
        type: 'url',
    };
    if (br) {
        params.br = br;
    }
    return buildApiUrl(params);
}

module.exports = {
    getPlaylistDetail,
    getSongInfo,
    searchSongs,
    buildSongUrl,
};
