import { prisma } from '@/lib/prisma';
import axios from 'axios';

export async function triggerWebhook(taskId: string, eventType: string, payload: unknown) {
  try {
    const webhooks = await prisma.agentWebhook.findMany({
      where: {
        task_id: taskId,
        events: {
          has: eventType,
        },
      },
    });

    if (webhooks.length === 0) {
      return;
    }

    const requests = webhooks.map(async (webhook) => {
      try {
        await axios.post(
          webhook.webhook_url,
          {
            jsonrpc: '2.0',
            method: 'a2a_task_event',
            params: {
              task_id: taskId,
              event: eventType,
              payload,
            },
            id: crypto.randomUUID(),
          },
          {
            headers: {
              'Content-Type': 'application/json',
            },
            timeout: 5000,
          }
        );
        console.log(`[Webhook] Sent ${eventType} to ${webhook.agent_id} (${webhook.webhook_url})`);
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(`[Webhook Error] Failed to send ${eventType} to ${webhook.agent_id}: ${message}`);
      }
    });

    await Promise.allSettled(requests);
  } catch (error) {
    console.error('[Webhook System Error] Failed to trigger webhooks:', error);
  }
}
