const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 3847;

// Forum channel IDs mapped to names
const FORUM_CHANNELS = {
  'new-music': '1464918784216137838',
  'mix-creation': '1464918785134821471',
  'remixes': '1464919192791810204',
  'label-submissions': '1464918785839333376',
  'playlist-pitching': '1464918786728661076',
  'own-playlist-strategy': '1464918787533832273',
  'paid-social-promo': '1464918788440068252',
  'landing-pages': '1464918789362552936',
  'event-networking': '1464918790360793242',
  'la-promoters-bookings': '1464918791623278697',
  'artist-collabs': '1464918793204531364',
  'artist-plays-support': '1464918794131738790',
  'mentors-advisors': '1464918795071258750',
  'growth-to-revenue': '1464918796052467806',
  'general': '1464918797302501457',
  'wins': '1464918798237958228',
  'resources': '1464918799470956723',
  'meeting-notes': '1464918800955736206'
};

const server = http.createServer((req, res) => {
  // CORS headers
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }

  if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
    const htmlPath = path.join(__dirname, 'index.html');
    fs.readFile(htmlPath, (err, data) => {
      if (err) {
        res.writeHead(500);
        res.end('Error loading form');
        return;
      }
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(data);
    });
    return;
  }

  if (req.method === 'POST' && req.url === '/submit') {
    let body = '';
    req.on('data', chunk => { body += chunk; });
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const filename = `submission-${timestamp}.json`;
        const filepath = path.join(__dirname, 'submissions', filename);
        
        // Ensure submissions directory exists
        const submissionsDir = path.join(__dirname, 'submissions');
        if (!fs.existsSync(submissionsDir)) {
          fs.mkdirSync(submissionsDir, { recursive: true });
        }
        
        // Add channel IDs to the data
        const enrichedData = {
          submittedAt: new Date().toISOString(),
          submittedBy: data.submittedBy || 'Dylan',
          threads: []
        };
        
        for (const [forumName, content] of Object.entries(data.forums || {})) {
          if (content.title && content.title.trim()) {
            enrichedData.threads.push({
              forumName,
              channelId: FORUM_CHANNELS[forumName],
              title: content.title.trim(),
              message: (content.message || '').trim() || 'Thread created via form submission.'
            });
          }
        }
        
        fs.writeFileSync(filepath, JSON.stringify(enrichedData, null, 2));
        
        console.log(`\n${'='.repeat(60)}`);
        console.log(`📬 NEW FORM SUBMISSION RECEIVED!`);
        console.log(`${'='.repeat(60)}`);
        console.log(`File: ${filename}`);
        console.log(`Threads to create: ${enrichedData.threads.length}`);
        enrichedData.threads.forEach(t => {
          console.log(`  - ${t.forumName}: "${t.title}"`);
        });
        console.log(`${'='.repeat(60)}\n`);
        
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ 
          success: true, 
          message: `Submitted! ${enrichedData.threads.length} threads will be created.`,
          filename 
        }));
      } catch (err) {
        console.error('Error processing submission:', err);
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ success: false, error: err.message }));
      }
    });
    return;
  }

  res.writeHead(404);
  res.end('Not found');
});

server.listen(PORT, () => {
  console.log(`\n🎸 Das Artist Development Form Server`);
  console.log(`${'='.repeat(40)}`);
  console.log(`Form URL: http://localhost:${PORT}`);
  console.log(`\nWaiting for submissions...\n`);
});
