const express = require('express');
const router = express.Router();
const db = require('../database');
const { triggerImmediateSync } = require('../sync/immediate');
const { getRoleMappings } = require('../utils/roleMappings');

// Map product slugs to database tier levels
const SLUG_TO_TIER = {
  "the-awakened": 1,
  "fire-elemental": 5,
  "fire-knight": 10,
  "fire-master": 15,
  "fire-legend": 20,
  "frost-elemental": 5,
  "frost-knight": 10,
  "frost-master": 15,
  "frost-legend": 20,
  "the-sovereign": 499
};

router.post('/paymenter', express.json(), async (req, res) => {
  const { event, user, product } = req.body;
  
  if (!user || !product) {
    return res.status(400).send('Missing required fields');
  }

  const discordId = user.discord_id;
  const slug = product.slug;
  const mappings = getRoleMappings();
  const roleId = mappings[slug];
  const tierLevel = SLUG_TO_TIER[slug] || 1;

  try {
    const client = req.app.locals.client;
    const guild = client.guilds.cache.get(process.env.GUILD_ID);
    let member = null;
    
    if (guild && discordId) {
      try { member = await guild.members.fetch(discordId); } catch(e) {}
    }

    if (event === 'subscription.created' || event === 'subscription.renewed') {
      // 1. Assign Discord Role
      if (member && roleId) await member.roles.add(roleId);
      
      // 2. Update PostgreSQL Database
      await db.query(
        `INSERT INTO subscriptions (discord_id, tier_level, status) 
         VALUES ($1, $2, 'active') 
         ON CONFLICT (discord_id) DO UPDATE SET tier_level = $2, status = 'active'`,
        [discordId, tierLevel]
      );
      
      console.log(`✅ Added role for ${slug} to ${discordId}`);
    } 
    else if (event === 'subscription.cancelled' || event === 'subscription.expired') {
      // 1. Remove Discord Role
      if (member && roleId) await member.roles.remove(roleId);

      // 2. Update PostgreSQL Database  
      await db.query(
        `UPDATE subscriptions SET status = 'cancelled' WHERE discord_id = $1`,
        [discordId]
      );
      
      console.log(`❌ Removed role for ${slug} from ${discordId}`);
    }

    // 3. Trigger Server Sync
    triggerImmediateSync();
    res.status(200).send('Webhook processed');

  } catch (error) {
    console.error('Webhook error:', error);
    res.status(500).send('Error processing webhook');
  }
});

module.exports = router;
