import { createClient } from 'redis';
import { NtfyClient, MessagePriority } from 'ntfy';

/**
 * NTFY_SERVER
 * NTFY_TOPIC
 * NTFY_USERNAME
 * NTFY_PASSWORD
 */

if (!process.env.NTFY_TOPIC) {
    console.log('$NTFY_TOPIC not set');
} else {
    console.log('Listening for new reports');

    const ntfy = new NtfyClient(process.env.NTFY_SERVER);
    const redis = createClient({
        url: process.env.REDIS,
    });

    redis.SUBSCRIBE('global', async (message) => {
        try {
            const event = JSON.parse(message);
            if (event.type != "ReportCreate") return;
            console.log('New report:', event.content);

            await ntfy.publish({
                title: `Report created (${event.content.type}, ${event.content.report_reason})`,
                message: event.additional_context || "No reason provided",
                iconURL: 'https://futacockinside.me/files/attention.png',
                actions: [
                    {
                        label: 'View report',
                        type: 'view',
                        url: `https://admin.revolt.chat/panel/reports/${event._id}`,
                        clear: true,
                    }
                ],
                priority: event.content.report_reason.includes('Illegal')
                    ? MessagePriority.HIGH
                    : MessagePriority.DEFAULT,
                topic: process.env.NTFY_TOPIC,
                authorization: process.env.NTFY_USERNAME && process.env.NTFY_PASSWORD
                  ? {
                    username: process.env.NTFY_USERNAME,
                    password: process.env.NTFY_PASSWORD,
                  }
                  : undefined,
            });
        } catch(e) {
            console.log(e);
        }
    });

    redis.connect();
}
