import type { NextApiRequest, NextApiResponse } from 'next';
import { WebhookPayload } from '@/types/webhook';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const payload: WebhookPayload = req.body;
    
    // Validate payload
    if (!payload.type || !payload.message || !payload.characterName || !payload.planetName) {
      return res.status(400).json({ error: 'Invalid payload' });
    }

    const webhookUrl = process.env.WEBHOOK_URL;
    
    if (!webhookUrl) {
      // If no external webhook URL is configured, just log the payload for testing
      console.log('🔔 Webhook payload (no external URL configured):', JSON.stringify(payload, null, 2));
      return res.status(200).json({ 
        success: true, 
        message: 'Webhook logged to console (no external URL configured)',
        payload 
      });
    }

    // Send webhook to external URL
    console.log('🔔 Sending webhook to external URL:', webhookUrl);
    
    // Use simple format with all the details
    const webhookPayload = {
      content: `${payload.message}\n**Character:** ${payload.characterName}\n**Planet:** ${payload.planetName}\n**Time:** ${new Date(payload.timestamp).toLocaleString()}`
    };
    
    console.log('📤 Sending payload:', JSON.stringify(webhookPayload, null, 2));
    
    const response = await fetch(webhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(webhookPayload),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('❌ Webhook failed:', response.status, response.statusText, errorText);
      throw new Error(`Webhook failed with status ${response.status}: ${errorText}`);
    }

    console.log('✅ Webhook sent successfully to external URL');
    res.status(200).json({ success: true, message: 'Webhook sent to external URL' });
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(500).json({ error: 'Failed to send webhook', details: (error as Error).message });
  }
}
