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

// GET - Fetch gallery images with pagination
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '0', 10)
    const limit = Math.min(parseInt(searchParams.get('limit') || '20', 10), 50)
    const from = page * limit
    const to = from + limit - 1

    const { data, error } = await supabase
      .from('gallery')
      .select('*')
      .order('created_at', { ascending: false })
      .range(from, to)

    if (error) throw error

    return NextResponse.json({ images: data || [] })
  } catch (error) {
    console.error('Gallery fetch error:', error)
    return NextResponse.json({ error: 'Failed to fetch gallery' }, { status: 500 })
  }
}

// POST - Submit image to gallery
export async function POST(request: Request) {
  try {
    // For now, just return a success response without storage upload
    // TODO: Set up Supabase Storage bucket for gallery images
    
    return NextResponse.json({ 
      success: true, 
      message: 'Gallery submission received (storage not configured yet)',
      image: {
        id: 'temp-id',
        image_url: 'temp-url',
        created_at: new Date().toISOString(),
        votes: 0
      }
    })
  } catch (error) {
    console.error('Gallery submit error:', error)
    return NextResponse.json({ error: 'Failed to submit to gallery', details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 })
  }
}
