const fetch = require("node-fetch");
const api_key = "Bearer pat-na1-446d4baf-0d69-49ff-91ed-2419c1ef76ba";


let ticketBaseURL = 'https://api.hubapi.com/crm/v3/objects/tickets/';
let ticketURLParams = '?associations=company,contact,conversations&properties=estimated_hours,impact_scope,ticket_priority,school_url,sandbox_url,issue_type,product_area,specific_product_area,hubspot_owner_id,subject,content,package_level,description'
let contactBaseURL = 'https://api.hubapi.com/crm/v3/objects/contacts/';
let reporterBaseURL = 'https://api.hubapi.com/crm/v3/owners/';
let contactURLParams = '?associations=company&properties=company,email,firstname,lastname';
let ticketID = ;
let ticket = {
    "fields": {
        "project": {
            "key": "SET"
        }
    }
};
let options = {
    method: "GET",
    headers: {
        Authorization: api_key,
    }
};


function wait(ms) {
    return new Promise(r => setTimeout(r, ms));
}

async function getTicketInfo(ticketID) {
    const ticketResp = await fetch(ticketBaseURL + ticketID + ticketURLParams, options);
    const ticketData = await ticketResp.json();
    const reporterResp = await fetch(reporterBaseURL + ticketData.properties.hubspot_owner_id, options);
    const reporterData = await reporterResp.json();
    const contactResp = await fetch(contactBaseURL + ticketData.associations.contacts.results[0].id + contactURLParams, options);
    const contactData = await contactResp.json();
    const jiraResp = await fetch('https://northpass.atlassian.net/rest/api/3/user/search?query=' + reporterData.email, {
        method: 'GET',
        headers: {
            'Authorization': `Basic Y2JlbmNpdmVuZ2FAbm9ydGhwYXNzLmNvbTpRcm1nSjVDbG00dUdvQXVWTnp5OTlFMzM=`,
            'Accept': 'application/json',
        },

    });
    const jiraData = await jiraResp.json();

    try {
        if (ticketData) {
            console.log(ticketData)
            console.log(ticketData.associations.companies.results);
            console.log(contactData)
            console.log(reporterData)
            if (ticketData.properties.hasOwnProperty('issue_type')) {
                ticket.fields.issuetype = { "name": ticketData.properties.issue_type };
            }
            if (ticketData.properties.hasOwnProperty('impact_scope') && ticketData.properties.issue_type == 'Bug') {
                ticket.fields.customfield_10170 = { "value": ticketData.properties.impact_scope }
            }

            if (ticketData.properties.hasOwnProperty('ticket_priority')) {
                ticket.fields.priority = { "name": ticketData.properties.ticket_priority }
            }
            if (ticketData.properties.hasOwnProperty('school_url')) {
                if (ticketData.properties.school_url.indexOf("https") == 0) {
                    ticket.fields.customfield_10171 = ticketData.properties.school_url
                } else {
                    ticket.fields.customfield_10171 = "https://" + ticketData.properties.school_url
                }
            }
            if (ticketData.properties.hasOwnProperty('sandbox_url') && ticketData.properties.issue_type == 'Change') {
                if (ticketData.properties.school_url.indexOf("https") == 0) {
                    ticket.fields.customfield_10172 = ticketData.properties.sandbox_url
                } else {
                    ticket.fields.customfield_10172 = "https://" + ticketData.properties.sandbox_url
                }
            }
            if (ticketData.properties.hasOwnProperty('product_area') && (ticketData.properties.issue_type !== 'Information' && ticketData.properties.issue_type !== 'Demo')) {
                ticket.fields.customfield_10168 = { "value": ticketData.properties.product_area }
            }
            if (ticketData.properties.hasOwnProperty('estimated_hours')) {
                if (ticketData.properties.estimated_hours) {
                    ticket.fields.timetracking = {
                        "originalEstimate": ticketData.properties.estimated_hours + 'h',
                        "remainingEstimate": ticketData.properties.estimated_hours + 'h'
                    }
                }
            }
            if (ticketData.properties.hasOwnProperty('specific_product_area') && (ticketData.properties.issue_type !== 'Information' && ticketData.properties.issue_type !== 'Demo')) {
                ticket.fields.customfield_10169 = { "value": ticketData.properties.specific_product_area }
            }
            if (ticketData.properties.hasOwnProperty('subject')) {
                ticket.fields.summary = ticketData.properties.subject
            }
            if (ticketData.properties.hasOwnProperty('content') && ticketData.properties.content !== null) {
                ticket.fields.description = {
                    "version": 1,
                    "type": "doc",
                    "content": [{
                        "type": "paragraph",
                        "content": [{
                            "type": "text",
                            "text": ticketData.properties.content
                        }]
                    }]
                }
            }
            if (ticketData.properties.hasOwnProperty('package_level')) {
                ticket.fields.customfield_10156 = { "value": ticketData.properties.package_level }
            }
            if (ticketData.associations.companies.results[0].hasOwnProperty('id')) {
                ticket.fields.customfield_10173 = ticketData.associations.companies.results[0].id
            }
            if (ticketData.properties.hasOwnProperty('due_date') && ticketData.properties.issue_type == 'Demo') {
                ticket.fields.duedate = ticketData.properties.due_date
            }
            if (ticketData.associations.hasOwnProperty('conversations')) {
                if (ticketData.associations.conversations.results[0].hasOwnProperty('id')) {
                    ticket.fields.customfield_10176 = ticketData.associations.conversations.results[0].id
                }
            }
            if (ticketID) {
                ticket.fields.customfield_10174 = ticketID.toString()
            }
            if (contactData.properties.hasOwnProperty('company')) {
                ticket.fields.customfield_10028 = [contactData.properties.company.replace(/\s/g, '')]
            }
            // No reason to use this yet. Will think about about keeping it or removing
            // if (contactData.properties.hasOwnProperty('email')) {
            //     ticket.fields.customerEmail = contactData.properties.email
            // } 
            if (jiraData[0].hasOwnProperty('accountId')) {
                ticket.fields.reporter = { "accountId": jiraData[0].accountId }
            }

            console.log(ticket)

            let bodyData = JSON.stringify(ticket)

            fetch('https://northpass.atlassian.net/rest/api/3/issue', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Basic Y2JlbmNpdmVuZ2FAbm9ydGhwYXNzLmNvbTpRcm1nSjVDbG00dUdvQXVWTnp5OTlFMzM=`,
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    body: bodyData
                })
                .then(response => {
                    console.log(
                        `Response: ${response.status} ${response.statusText}`
                    );
                    return response.text();
                })
                .then(text => console.log(text))
                .catch(err => console.error(err));
            return ticket
        } else {
            console.log("complete");
        }
    } catch (err) {
        console.log(err);
    };
};

getTicketInfo(ticketID);