import { NextApiRequest, NextApiResponse } from 'next';

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 = req.body;
    
    // Check if this is a test request
    if (payload.type === 'test') {
      const missing = [];
      if (!payload.zulipUrl) missing.push('zulipUrl');
      if (!payload.zulipEmail) missing.push('zulipEmail');
      if (!payload.zulipApiKey) missing.push('zulipApiKey');
      if (!payload.zulipStream) missing.push('zulipStream');
      
      if (missing.length > 0) {
        return res.status(400).json({ error: `Missing required Zulip configuration: ${missing.join(', ')}` });
      }

      const zulipUrl = payload.zulipUrl;
      const zulipEmail = payload.zulipEmail;
      const zulipApiKey = payload.zulipApiKey;
      const zulipStream = payload.zulipStream;

      const topic = 'Test-Webhook-Test';
      const content = '🧪 **Test Webhook**\nThis is a test message from EvePI to verify Zulip integration is working correctly.\n\n**Time:** ' + new Date().toLocaleString();
      
      const zulipPayload = new URLSearchParams();
      zulipPayload.append('type', 'stream');
      zulipPayload.append('to', zulipStream);
      zulipPayload.append('topic', topic);
      zulipPayload.append('content', content);
      
      const auth = Buffer.from(`${zulipEmail}:${zulipApiKey}`).toString('base64');
      
      const response = await fetch(zulipUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': `Basic ${auth}`
        },
        body: zulipPayload.toString()
      });

      if (!response.ok) {
        const errorText = await response.text();
        return res.status(400).json({ 
          error: 'Zulip test webhook failed', 
          details: errorText,
          status: response.status 
        });
      }

      const result = await response.text();
      
      return res.status(200).json({ 
        success: true, 
        message: 'Test webhook sent successfully to Zulip',
        result 
      });
    }
    
    // Validate payload for normal webhook
    if (!payload.type || !payload.message || !payload.characterName || !payload.planetName) {
      return res.status(400).json({ error: 'Invalid payload' });
    }

    const zulipUrl = payload.zulipUrl;
    const zulipEmail = payload.zulipEmail;
    const zulipApiKey = payload.zulipApiKey;
    const zulipStream = payload.zulipStream;
    
    if (!zulipUrl || !zulipEmail || !zulipApiKey || !zulipStream) {
      return res.status(400).json({ error: 'Missing required Zulip configuration' });
    }

    // Create topic in format: CharacterName-PlanetName-ActionType
    const actionType = payload.type.replace(/_/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase());
    const topic = `${payload.characterName}-${payload.planetName}-${actionType}`;
    
    // Format content with all the details
    const content = `${payload.message}\n**Character:** ${payload.characterName}\n**Planet:** ${payload.planetName}\n**Time:** ${new Date(payload.timestamp).toLocaleString()}`;
    
    // Create Zulip API payload
    const zulipPayload = new URLSearchParams();
    zulipPayload.append('type', 'stream');
    zulipPayload.append('to', zulipStream);
    zulipPayload.append('topic', topic);
    zulipPayload.append('content', content);
    
    console.log('🔔 Sending webhook to Zulip:', zulipUrl);
    console.log('📤 Topic:', topic);
    console.log('📤 Content:', content);
    
    const response = await fetch(zulipUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Basic ${Buffer.from(`${zulipEmail}:${zulipApiKey}`).toString('base64')}`
      },
      body: zulipPayload.toString(),
    });

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

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