import prisma from './prisma'

interface WebhookPayload {
  event: 'DEPOSIT_SUCCESS' | 'ORDER_UPDATE'
  [key: string]: any
}

export async function sendH2HWebhook(userId: string, payload: WebhookPayload) {
  try {
    // Find the first active API key that has a webhookUrl for this user
    const apiKey = await prisma.apiKey.findFirst({
      where: {
        userId,
        isActive: true,
        webhookUrl: { not: null },
      },
      orderBy: { createdAt: 'desc' }
    })

    if (!apiKey || !apiKey.webhookUrl) return

    console.log(`[H2H Webhook] Firing ${payload.event} to ${apiKey.webhookUrl}`)

    // Fire & Forget POST request
    fetch(apiKey.webhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'User-Agent': 'AmaneNime-H2H-Webhook/1.0',
        'x-webhook-event': payload.event,
      },
      body: JSON.stringify(payload)
    }).catch(e => {
      console.warn(`[H2H Webhook] Failed to send payload to ${apiKey.webhookUrl}:`, e.message)
    })
    
  } catch (error: any) {
    console.error('[H2H Webhook] Error preparing webhook:', error.message)
  }
}
