// src/routes/webhook.js
// Paymenter webhook handler for subscription events

const express = require('express');
const crypto = require('crypto');
const db = require('../database');
const { sendLinkingEmail } = require('../email');
const { assignDiscordRole, updateSubscriptionRoles } = require('../discordService');
const verifyBillingWebhook = require('../middleware/verifyWebhook');
const validateBillingPayload = require('../middleware/validateWebhook');

const router = express.Router();

router.post('/billing', verifyBillingWebhook, validateBillingPayload, async (req, res) => {
    const { event, discord_id, tier, customer_email, customer_name, subscription_id } = req.body;

    console.log(`[Webhook] Received ${event} for ${customer_email}`);

    try {
        if (event === 'subscription.created') {
            if (discord_id) {
                // User already linked - assign role immediately
                await assignDiscordRole(discord_id, tier);
                return res.status(200).json({ message: 'Role assigned' });
            } else {
                // User not linked yet - generate token and send email
                const token = crypto.randomBytes(32).toString('hex');
                
                const stmt = db.prepare(`
                    INSERT INTO link_tokens (token, email, tier, subscription_id) 
                    VALUES (?, ?, ?, ?)
                `);
                stmt.run(token, customer_email, tier, subscription_id);

                await sendLinkingEmail(customer_name || 'Subscriber', customer_email, token);
                console.log(`[Webhook] Sent linking email to ${customer_email}`);
                return res.status(200).json({ message: 'Email sent' });
            }
        }

        if (event === 'subscription.upgraded' || event === 'subscription.downgraded') {
            if (discord_id) {
                await updateSubscriptionRoles(discord_id, tier);
                return res.status(200).json({ message: 'Roles updated' });
            }
        }

        if (event === 'subscription.cancelled') {
            if (discord_id) {
                await updateSubscriptionRoles(discord_id, null); // Remove all roles
                return res.status(200).json({ message: 'Roles removed' });
            }
        }
        
        res.status(200).json({ message: 'Event acknowledged' });
    } catch (error) {
        console.error('[Webhook] Processing failed:', error);
        return res.status(500).json({ error: 'Internal error' });
    }
});

module.exports = router;
