const fetch = require("node-fetch");
const { errorCode } = require("../constant");
const { KHQRResponse } = require("../model");

class SourceInfo {
    constructor(appIconUrl, appName, appDeepLinkCallback) {
        this.appIconUrl = appIconUrl || null;
        this.appName = appName || null;
        this.appDeepLinkCallback = appDeepLinkCallback || null;
    }
}

function isValidLink(link) {
    try {
        let url = new URL(link);

        if (url.pathname != "/v1/generate_deeplink_by_qr") return false;
    } catch (error) {
        return false;
    }
    return true;
}

async function callDeepLinkAPI(url, data) {
    let response = await fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
        timeout: 45 * 1000,
    });

    try {
        JSON.parse(response.text())
    } catch (error) {
        throw KHQRResponse(null, errorCode.CONNECTION_TIMEOUT);
    }

    if (response == undefined)
        throw KHQRResponse(null, errorCode.CONNECTION_TIMEOUT);

    return response;
}

module.exports = { isValidLink, callDeepLinkAPI, SourceInfo };
