// routes/webhook.routes.js
const express = require('express');
const router = express.Router();
const WebhookService = require('../services/webhook.service');

const webhookService = new WebhookService();

// GitHub webhook endpoint
router.post('/webhook', async (req, res) => {
  try {
    const signature = req.headers['x-hub-signature-256'];
    const eventType = req.headers['x-github-event'];
    const deliveryId = req.headers['x-github-delivery'];
    const userAgent = req.headers['user-agent'];
    
    console.log('🔔 GitHub webhook received:');
    console.log(`- Event Type: ${eventType}`);
    console.log(`- Delivery ID: ${deliveryId}`);
    console.log(`- User Agent: ${userAgent}`);
    console.log(`- Signature: ${signature ? 'Present' : 'Missing'}`);
    console.log(`- Payload Size: ${JSON.stringify(req.body).length} bytes`);
    console.log(`- Timestamp: ${new Date().toISOString()}`);

    // Verify webhook signature if secret is configured
    if (process.env.GITHUB_WEBHOOK_SECRET) {
      const rawBody = JSON.stringify(req.body);
      const isValidSignature = webhookService.verifySignature(rawBody, signature);
      
      if (!isValidSignature) {
        console.warn('Invalid webhook signature - potential security issue');
        return res.status(401).json({
          success: false,
          message: 'Invalid webhook signature'
        });
      }
    } else {
      console.warn('GitHub webhook secret not configured - skipping signature verification');
    }

    // Attach delivery_id into payload for downstream persistence convenience
    const payloadWithDelivery = { ...req.body, delivery_id: deliveryId };

    // Process the webhook event
    if (eventType) {
      await webhookService.processWebhookEvent(eventType, payloadWithDelivery);
    }

    // Log the webhook event
    await webhookService.logWebhookEvent(
      eventType || 'unknown',
      req.body.action || 'unknown',
      req.body.repository?.full_name || 'unknown',
      {
        delivery_id: deliveryId,
        event_type: eventType,
        action: req.body.action,
        repository: req.body.repository?.full_name,
        sender: req.body.sender?.login
      },
      deliveryId,
      payloadWithDelivery
    );

    res.status(200).json({
      success: true,
      message: 'Webhook processed successfully',
      event_type: eventType,
      delivery_id: deliveryId
    });

  } catch (error) {
    console.error('Error processing webhook:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to process webhook',
      error: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error'
    });
  }
});

// Get recent webhook events (for debugging)
router.get('/webhook/events', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 50;
    const events = await webhookService.getRecentWebhookEvents(limit);
    
    res.json({
      success: true,
      data: {
        events,
        total: events.length,
        limit
      }
    });
  } catch (error) {
    console.error('Error fetching webhook events:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch webhook events'
    });
  }
});

// Webhook health check
router.get('/webhook/health', (req, res) => {
  res.json({
    success: true,
    message: 'Webhook service is healthy',
    timestamp: new Date().toISOString(),
    webhook_secret_configured: !!process.env.GITHUB_WEBHOOK_SECRET
  });
});

module.exports = router;
