const db = require("../config/db");
const webpush = require('web-push');

const VAPID_PUBLIC_KEY = process.env.VAPID_PUBLIC_KEY;
const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY;

webpush.setVapidDetails(
    'mailto:rozenrod320@gmail.com',
    VAPID_PUBLIC_KEY,
    VAPID_PRIVATE_KEY
);

class Notification {
    async sendAll({ title, body, page }) {
        const sql = `
            SELECT * FROM subscription
            ORDER BY id
        `;

        db.all(sql, async (err, rows) => {
            if (err) {
                console.error('DB error:', err.message);
                return;
            }

            if (!rows.length) {
                console.log(`🐑 No subscriptions`);
                return;
            }

            console.log(`📨 Sending notification to ${rows.length} subscriptions...`);

            const payload = JSON.stringify({
                title: title ?? "Тестове повідомлення",
                body: body ?? "Ви успішно підписалися на отримання push повідомлень!",
                url: `https://${process.env.DOMAIN}${page ?? ""}`
            });

            const results = await Promise.allSettled(rows.map(row => {
                const subscription = {
                    endpoint: row.endpoint,
                    keys: JSON.parse(row.keys),
                };
                return webpush.sendNotification(subscription, payload);
            }));

            const failed = results.filter(r => r.status === 'rejected').length;
            console.log(`✅ Sent: ${rows.length - failed}, ❌ Failed: ${failed}`);
        });
    }

    async sendSheep({ sheep_id, title, body, page }) {
        const sql = `
            SELECT * FROM subscription
            WHERE sheep_id = ?
            ORDER BY id
        `;

        db.all(sql, [sheep_id], async (err, rows) => {
            if (err) {
                console.error('DB error:', err.message);
                return;
            }

            if (!rows.length) {
                console.log(`🐑 No subscriptions found for sheep_id: ${sheep_id}`);
                return;
            }

            console.log(`📨 Sending notification to ${rows.length} subscriptions...`);

            const payload = JSON.stringify({
                title: title ?? "Тестове повідомлення",
                body: body ?? "Ви успішно підписалися на отримання push повідомлень!",
                url: `https://${process.env.DOMAIN}${page ?? ""}`
            });

            const results = await Promise.allSettled(rows.map(row => {
                const subscription = {
                    endpoint: row.endpoint,
                    keys: JSON.parse(row.keys),
                };
                return webpush.sendNotification(subscription, payload);
            }));

            const failed = results.filter(r => r.status === 'rejected').length;
            console.log(`✅ Sent: ${rows.length - failed}, ❌ Failed: ${failed}`);
        });
    }

    async sendGroup({ group_id, title, body, page }) {
        const sql = `
            SELECT 
                subscription.*
            FROM 
                subscription
            JOIN 
                sheeps
            ON 
                sheeps.id = subscription.sheep_id
            WHERE 
                sheeps.group_id = ?
            ORDER BY 
                subscription.id;
        `;

        db.all(sql, [group_id], async (err, rows) => {
            if (err) {
                console.error('DB error:', err.message);
                return;
            }

            if (!rows.length) {
                console.log(`🐑 No subscriptions found for group_id: ${group_id}`);
                return;
            }

            console.log(`📨 Sending notification to ${rows.length} subscriptions...`);

            const payload = JSON.stringify({
                title: title ?? "Тестове повідомлення",
                body: body ?? "Ви успішно підписалися на отримання push повідомлень!",
                url: `https://${process.env.DOMAIN}${page ?? ""}`
            });

            const results = await Promise.allSettled(rows.map(row => {
                const subscription = {
                    endpoint: row.endpoint,
                    keys: JSON.parse(row.keys),
                };
                return webpush.sendNotification(subscription, payload);
            }));

            const failed = results.filter(r => r.status === 'rejected').length;
            console.log(`✅ Sent: ${rows.length - failed}, ❌ Failed: ${failed}`);
        });
    }

    async sendStandAdd({title, body, page }) {
        const sql = `
            SELECT 
                subscription.*
            FROM 
                subscription
            JOIN 
                sheeps
                ON sheeps.id = subscription.sheep_id
            JOIN 
                possibilities
                ON possibilities.sheep_id = sheeps.id
            WHERE 
                possibilities.can_add_stand = '1'
            ORDER BY 
                subscription.id;
        `;

        db.all(sql, async (err, rows) => {
            if (err) {
                console.error('DB error:', err.message);
                return;
            }

            if (!rows.length) {
                console.log(`🐑 No subscriptions found for sheep_id: ${sheep_id}`);
                return;
            }

            console.log(`📨 Sending notification to ${rows.length} subscriptions...`);

            const payload = JSON.stringify({
                title: title ?? "Тестове повідомлення",
                body: body ?? "Ви успішно підписалися на отримання push повідомлень!",
                url: `https://${process.env.DOMAIN}${page ?? ""}`
            });

            const results = await Promise.allSettled(rows.map(row => {
                const subscription = {
                    endpoint: row.endpoint,
                    keys: JSON.parse(row.keys),
                };
                return webpush.sendNotification(subscription, payload);
            }));

            const failed = results.filter(r => r.status === 'rejected').length;
            console.log(`✅ Sent: ${rows.length - failed}, ❌ Failed: ${failed}`);
        });
    }

    async sendEndpoint({ endpoint, keys, title, body, page }) {
        const payload = JSON.stringify({
            title: title ?? "Тестове повідомлення",
            body: body ?? "Ви успішно підписалися на отримання push повідомлень!",
            url: `https://${process.env.DOMAIN}${page ?? ""}`
        });

        const subscription = {
            endpoint,
            keys: typeof keys === "string" ? JSON.parse(keys) : keys
        };

        await webpush.sendNotification(subscription, payload);
        console.log("✅ Push sent");
    }
};

module.exports = new Notification();