Fix this code

const axios = require('axios');
const cheerio = require('cheerio');
const https = require('https');

// Configure HTTPS agent to disable certificate validation (not recommended for production)
const agent = new https.Agent({
    rejectUnauthorized: false
});

/**
 * Fetch parcel data from the given URL.
 * @param {string} url - The URL to fetch data from.
 * @returns {Object} - Parcel data.
 */
async function getParcelData(url) {
    try {
        const response = await axios.get(url, { httpsAgent: agent });
        const html = response.data;
        const $ = cheerio.load(html);

        const parcel = {};

        // Parse parcel information
        parseParcelInformation($, parcel);

        // Parse permits data
        parcel.permits = parsePermitsData($);

        // Additional data processing
        parcel.solarDate = getSolarDate(parcel.permits);
        parcel.trueup = checkIncreaseInEnergyUsage(parcel.permits, parcel.solarDate);

        console.log(parcel);
        return parcel;
    } catch (error) {
        console.error('Error fetching data:', error);
        throw error; // Re-throw the error to handle it elsewhere if needed
    }
}

/**
 * Parse parcel information from the Cheerio instance.
 * @param {CheerioStatic} $ - Cheerio instance.
 * @param {Object} parcel - Parcel object to populate.
 */
function parseParcelInformation($, parcel) {
    const parcelInfoTable = $('#j_id0\\:parcelInformation\\:j_id166\\:0\\:j_id167');
    const rows = parcelInfoTable.find('.row');

    const address = getDataFromRow($(rows[0]));
    const addressMatches = address.match(/^(.*?)((?:DR|ST|LN|PL|AVE|CIR|BLVD|WAY|WY|ROAD|RD))(.*?)(\d+)$/im);

    if (addressMatches) {
        const [, street, streetType, city, zip] = addressMatches;
        parcel.street = `${street.trim()} ${streetType.trim()}`;
        parcel.city = city.trim();
        parcel.zip = zip.trim();
    } else {
        console.log("Invalid street address format.");
        // If address format is invalid, set placeholder values or handle as appropriate
        parcel.street = "Unknown";
        parcel.city = "Unknown";
        parcel.zip = "Unknown";
    }

    parcel.number = getDataFromRow($(rows[1])).trim();

    const coordinates = getDataFromRow($(rows[3])).split('/');
    const latitude = coordinates[0].trim();
    const longitude = coordinates[1].trim();
    parcel.coordinates = { latitude, longitude };
}

/**
 * Parse permits data from the Cheerio instance.
 * @param {CheerioStatic} $ - Cheerio instance.
 * @returns {Array} - Array of permit objects.
 */
function parsePermitsData($) {
    const permits = [];

    $('#permitDataTable tr').each((index, row) => {
        if (index > 0) {
            const cells = $(row).find('td');

            const permit = {
                number: cells.eq(0).text().trim(),
                link: cells.eq(0).find('a').attr('href'),
                status: cells.eq(1).text().trim(),
                description: cells.eq(2).text().trim(),
                issueDate: formatDate(cells.eq(3).text().trim()),
                type: getPermitType(cells.eq(0).text().trim()),
                expirationDate: formatDate(cells.eq(5).text().trim())
            };

            permits.push(permit);
        }
    });

    return permits;
}

/**
 * Get permit type based on permit number.
 * @param {string} permitNumber - Permit number.
 * @returns {string|null} - Permit type.
 */
function getPermitType(permitNumber) {
    if (permitNumber.includes('EL')) {
        return 'Electrical';
    } else if (permitNumber.includes('SL')) {
        return 'Solar';
    } else {
        return null;
    }
}

/**
 * Get solar date from permits data.
 * @param {Array} permits - Array of permit objects.
 * @returns {string|null} - Solar date.
 */
function getSolarDate(permits) {
    for (const permit of permits) {
        if (permit.type === 'Solar') {
            return permit.issueDate;
        }
    }
    return null;
}

/**
 * Check for an increase in energy usage after solar permit issue date.
 * @param {Array} permits - Array of permit objects.
 * @param {string} solarDate - Solar permit issue date.
 * @returns {Object} - Object indicating increase and old panels status.
 */
function checkIncreaseInEnergyUsage(permits, solarDate) {
    const increase = permits.some(permit => {
        const description = permit.description.toLowerCase();
        const keywords = ["air conditioner", "a/c", "hvac", "pool", "spa"];
        const issueDate = new Date(permit.issueDate);

        return keywords.some(keyword => description.includes(keyword)) && issueDate > new Date(solarDate);
    });

    const oldPanels = new Date(solarDate) < new Date('2015-01-01');

    return { increase, oldPanels };
}

/**
 * Extract data from a row in the table.
 * @param {Cheerio} row - Row element.
 * @returns {string} - Extracted data.
 */
function getDataFromRow(row) {
    const cells = row.find('div');
    const data = cells.eq(1);
    return data.text().trim();
}

/**
 * Format date string to 'MM / DD / YYYY' format.
 * @param {string} dateStr - Date string.
 * @returns {string} - Formatted date string.
 */
function formatDate(dateStr) {
    const date = new Date(dateStr);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const year = date.getFullYear();
    return `${month} / ${day} / ${year}`;
}

module.exports = {
    getParcelData
};