module.exports = {
    name: "Get Rockstar Games Service Status",

    description: "Fetches the current service status from the Rockstar Games support website. By Domin0221",

    category: "Internet Stuff",

    inputs: [
        {
            "id": "action",
            "name": "Action",
            "description": "Acceptable Types: Action\n\nDescription: Executes this block.",
            "types": ["action"]
        }
    ],

    options: [],

    outputs: [
        {
            "id": "action",
            "name": "Action",
            "description": "Type: Action\n\nDescription: Executes the following blocks when this block finishes its task successfully.",
            "types": ["action"]
        },
        {
            "id": "error_action",
            "name": "Error Action",
            "description": "Type: Action\n\nDescription: Executes the following blocks when this block encounters an error.",
            "types": ["action"]
        },
        {
            "id": "status_message",
            "name": "Status Message",
            "description": "Type: Text\n\nDescription: The overall status message (e.g., 'All services operational').",
            "types": ["text", "unspecified"]
        },
        {
            "id": "last_updated",
            "name": "Last Updated",
            "description": "Type: Text\n\nDescription: The raw text of when the status was last updated.",
            "types": ["text", "unspecified"]
        },
        {
            "id": "last_updated_unix",
            "name": "Last Updated UNIX Timestamp",
            "description": "Type: Number\n\nDescription: The UNIX timestamp (in seconds) of the last update.",
            "types": ["number", "unspecified"]
        },
        {
            "id": "service_status",
            "name": "Service Status",
            "description": "Type: Object\n\nDescription: An object containing all the categories and their respective service statuses.",
            "types": ["object", "unspecified"]
        },
        {
            "id": "error",
            "name": "Error",
            "description": "Type: Text\n\nDescription: The error message if the fetch or parse fails.",
            "types": ["text", "unspecified"]
        }
    ],

    async code(cache) {
        const cheerio = await this.require('cheerio');

        const url = 'https://support.rockstargames.com/servicestatus';
        const headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        };

        fetch(url, { headers })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.text();
            })
            .then(html => {
                const $ = cheerio.load(html);

                // Extract Overall Status and Metadata
                const overallStatus = $('h5[data-testid="status-hero-heading"]').text().trim();
                const lastUpdated = $('p[data-testid="status-hero-metadata"]').text().trim();
                
                // Convert metadata string to UNIX timestamp (seconds)
                let unixTimestamp = null;
                try {
                    const cleanDateStr = lastUpdated.replace('As of ', '').replace(' @', '');
                    unixTimestamp = Math.floor(new Date(cleanDateStr).getTime() / 1000);
                } catch (err) {
                    console.log('Error parsing date:', err);
                }

                // Extract detailed service statuses
                const statusObject = {};

                $('h6[data-testid="status-section-heading"]').each((i, el) => {
                    const category = $(el).text().trim();
                    statusObject[category] = {};

                    const sectionContainer = $(el).parent();

                    sectionContainer.find('p[data-testid^="status-item-"]').each((j, pEl) => {
                        const subKey = $(pEl).text().trim();
                        const itemWrapper = $(pEl).parent();
                        const rawStatus = itemWrapper.find('span').text().trim().toLowerCase();

                        let status = "Down";
                        if (rawStatus.includes('operational')) {
                            status = "Operational";
                        } else if (rawStatus.includes('limited')) {
                            status = "Limited";
                        }

                        if (subKey) {
                            statusObject[category][subKey] = status;
                        }
                    });
                });

                // Store outputs
                this.StoreOutputValue(overallStatus, "status_message", cache);
                this.StoreOutputValue(lastUpdated, "last_updated", cache);
                this.StoreOutputValue(unixTimestamp, "last_updated_unix", cache);
                this.StoreOutputValue(statusObject, "service_status", cache);

                // Trigger next block action
                this.RunNextBlock("action", cache);
            })
            .catch(error => {
                // Store error and trigger error action
                this.StoreOutputValue(error.message, "error", cache);
                this.RunNextBlock("error_action", cache);
            });
    }
}