import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase'

export async function GET() {
  try {
    const { data: leads, error } = await supabase
      .from('leads')
      .select('*')
      .order('created_at', { ascending: false })
    
    if (error) throw error
    
    return NextResponse.json({ leads: leads || [] })
  } catch (error) {
    console.error('Supabase error:', error)
    return NextResponse.json({ leads: [], error: 'Failed to fetch' }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    
    const lead = {
      name: body.name,
      business_name: body.businessName || body.business_name || null,
      phone: body.phone || null,
      email: body.email || null,
      source: body.source || null,
      status: body.status || 'new',
      notes: body.notes || null,
    }
    
    const { data, error } = await supabase
      .from('leads')
      .insert([lead])
      .select()
    
    if (error) {
      console.error('Supabase insert error:', error)
      return NextResponse.json({ error: error.message }, { status: 500 })
    }
    
    return NextResponse.json({ success: true, lead: data?.[0] })
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json({ error: 'Failed to save' }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json()
    const { id, ...updates } = body
    
    const { data, error } = await supabase
      .from('leads')
      .update(updates)
      .eq('id', id)
      .select()
    
    if (error) throw error
    
    return NextResponse.json({ success: true, lead: data?.[0] })
  } catch (error) {
    return NextResponse.json({ error: 'Failed to update' }, { status: 500 })
  }
}
