import { supabaseAdmin } from '../../lib/supabase';

export default async function handler(req, res) {
  console.log('=== UPDATE DEVLOG API CALLED (Supabase) ===');
  console.log('Method:', req.method);
  console.log('Body:', JSON.stringify(req.body, null, 2));

  if (req.method !== 'POST') {
    console.log('Method not allowed:', req.method);
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const data = req.body;
    console.log('Received data type:', typeof data);
    console.log('Is array:', Array.isArray(data));
    
    // Validate that data is an array
    if (!Array.isArray(data)) {
      console.log('Invalid data format - not an array');
      return res.status(400).json({ error: 'Data must be an array' });
    }

    // Process each entry for Supabase
    const results = [];
    
    for (const entry of data) {
      // Ensure content is an array
      const content = Array.isArray(entry.content) ? entry.content : [];
      
      // Create clean entry with required fields
      const cleanEntry = {
        title: entry.title || '',
        date: entry.date || '',
        description: entry.description || '',
        slug: entry.slug || '',
        image: entry.image || '',
        content: content,
        updated_at: new Date().toISOString()
      };
      
      console.log('Processing entry:', cleanEntry);
      
      // Use UPSERT (insert or update based on slug)
      const { data: result, error } = await supabaseAdmin
        .from('devlog_entries')
        .upsert(cleanEntry, { 
          onConflict: 'slug',
          returning: 'minimal'
        });
      
      if (error) {
        console.error('Supabase upsert error:', error);
        throw error;
      }
      
      results.push(result);
      console.log('Entry upserted successfully:', cleanEntry.slug);
    }
    
    console.log('All entries processed successfully');
    res.status(200).json({ 
      message: 'DevLog updated successfully in Supabase', 
      count: data.length 
    });
    
  } catch (error) {
    console.error('Error updating devlog in Supabase:', error);
    res.status(500).json({ 
      error: 'Failed to update devlog in Supabase', 
      details: error.message,
      stack: error.stack 
    });
  }
}
