import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

interface ConsumeOneTimePrekeyRequest {
  target_user_id: string
}

serve(async (req) => {
  // Handle CORS
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

  try {
    // Create a Supabase client with the Auth context of the logged in user.
    const supabaseClient = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_ANON_KEY') ?? '',
      {
        global: {
          headers: { Authorization: req.headers.get('Authorization')! },
        },
      }
    )

    // Get the current user
    const {
      data: { user },
    } = await supabaseClient.auth.getUser()

    if (!user) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      })
    }

    // Parse request body
    const { target_user_id }: ConsumeOneTimePrekeyRequest = await req.json()

    if (!target_user_id) {
      return new Response(JSON.stringify({ error: 'target_user_id is required' }), {
        status: 400,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      })
    }

    console.log(`Consuming one-time pre-key for user: ${target_user_id}`)

    // Get and consume (delete) the oldest one-time pre-key for the target user
    const { data: prekey, error } = await supabaseClient
      .from('one_time_prekeys')
      .delete()
      .eq('user_id', target_user_id)
      .order('created_at')
      .limit(1)
      .select('id, public_key')
      .single()

    if (error) {
      console.error('Error consuming one-time pre-key:', error)
      return new Response(JSON.stringify({ error: 'Failed to consume one-time pre-key' }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      })
    }

    if (!prekey) {
      console.log(`No one-time pre-keys available for user: ${target_user_id}`)
      // Return null to indicate no pre-key was available
      return new Response(JSON.stringify(null), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      })
    }

    console.log(`Successfully consumed one-time pre-key: ${prekey.id} for user: ${target_user_id}`)

    // Return the consumed pre-key data
    return new Response(JSON.stringify({
      key_id: prekey.id,
      public_key: prekey.public_key,
    }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    })

  } catch (error) {
    console.error('Unexpected error:', error)
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    })
  }
})
