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 + 'prime-salt').digest('hex').slice(0, 16)
}

// GET - retrieve current vote count
export async function GET() {
  try {
    const { count, error } = await supabase
      .from('prime_declarations')
      .select('*', { count: 'exact', head: true })

    if (error) {
      console.error('Vote count error:', error)
      return NextResponse.json({ count: 0 })
    }

    return NextResponse.json({ count: count || 0 })
  } catch (error) {
    console.error('Vote GET error:', error)
    return NextResponse.json({ count: 0 })
  }
}

// POST - add a vote
export async function POST(request: Request) {
  try {
    // 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
    const { data: existing } = await supabase
      .from('prime_declarations')
      .select('id')
      .eq('ip_hash', ipHash)
      .single()

    if (existing) {
      // Already voted - return current count without error
      const { count } = await supabase
        .from('prime_declarations')
        .select('*', { count: 'exact', head: true })

      return NextResponse.json({ count: count || 0, alreadyVoted: true })
    }

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

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

    // Get new count
    const { count } = await supabase
      .from('prime_declarations')
      .select('*', { count: 'exact', head: true })

    return NextResponse.json({ count: count || 0, alreadyVoted: false })
  } catch (error) {
    console.error('Vote POST error:', error)
    return NextResponse.json({ error: 'Failed to record vote' }, { status: 500 })
  }
}
