import { NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase'
import { galleryRatelimit, getClientIp, checkRateLimit } from '@/lib/ratelimit'
import crypto from 'crypto'

// Hash IP for privacy while preventing duplicates
function hashIp(ip: string): string {
  return crypto.createHash('sha256').update(ip + 'gallery-salt').digest('hex').slice(0, 16)
}

// POST - vote on a gallery image
export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const galleryId = params.id
    if (!galleryId) {
      return NextResponse.json({ error: 'Invalid gallery ID' }, { status: 400 })
    }

    // Rate limit check
    const ip = getClientIp(request)
    const { success, error } = await checkRateLimit(galleryRatelimit, ip)
    if (!success) return error

    const ipHash = hashIp(ip)

    // Check if this IP already voted for this image
    const { data: existing } = await supabase
      .from('gallery_votes')
      .select('id')
      .eq('gallery_id', galleryId)
      .eq('ip_hash', ipHash)
      .single()

    if (existing) {
      // Already voted - return current count without error
      const { data: galleryItem } = await supabase
        .from('gallery')
        .select('votes')
        .eq('id', galleryId)
        .single()

      return NextResponse.json({
        votes: galleryItem?.votes || 0,
        alreadyVoted: true
      })
    }

    // Insert new vote
    const { error: insertError } = await supabase
      .from('gallery_votes')
      .insert({
        gallery_id: galleryId,
        ip_hash: ipHash,
        created_at: new Date().toISOString()
      })

    if (insertError) {
      console.error('Gallery vote insert error:', insertError)
      return NextResponse.json({ error: 'Failed to record vote' }, { status: 500 })
    }

    // Increment vote count on gallery item using RPC
    const { error: updateError } = await supabase.rpc('increment_gallery_votes', { row_id: galleryId })

    if (updateError) {
      console.error('Gallery vote increment error:', updateError)
      // Fallback: manually increment (race condition possible but better than failing)
      const { data: current } = await supabase
        .from('gallery')
        .select('votes')
        .eq('id', galleryId)
        .single()

      const newVotes = (current?.votes || 0) + 1

      await supabase
        .from('gallery')
        .update({ votes: newVotes })
        .eq('id', galleryId)

      return NextResponse.json({
        votes: newVotes,
        alreadyVoted: false
      })
    }

    // Fetch the updated count to return
    const { data: updated } = await supabase
      .from('gallery')
      .select('votes')
      .eq('id', galleryId)
      .single()

    return NextResponse.json({
      votes: updated?.votes || 1,
      alreadyVoted: false
    })
  } catch (error) {
    console.error('Gallery vote error:', error)
    return NextResponse.json({ error: 'Failed to record vote' }, { status: 500 })
  }
}
