import crypto from "crypto";
import { db } from "@epicure/db";
import { adminWebhooks, adminWebhookDeliveries } from "@epicure/db";
import { eq } from "@epicure/db";
import { deliverWebhook } from "@/lib/webhook-delivery";

// Site-wide ops events — distinct from WEBHOOK_EVENTS in lib/webhooks.ts,
// which are per-user events on a user's own data. These fire regardless of
// who's involved, for ops alerting (Slack/Discord/etc via a generic
// incoming webhook), so only admins can subscribe to them.
export const ADMIN_WEBHOOK_EVENTS = [
  "user.signed_up",
  "support_ticket.created",
  "report.filed",
] as const;

export type AdminWebhookEvent = (typeof ADMIN_WEBHOOK_EVENTS)[number];

export async function dispatchAdminWebhook(event: AdminWebhookEvent, payload: object) {
  const hooks = await db.select().from(adminWebhooks).where(eq(adminWebhooks.active, true));
  const filtered = hooks.filter((h) => h.events.length === 0 || h.events.includes(event));

  await Promise.allSettled(
    filtered.map(async (hook) => {
      const { statusCode, success } = await deliverWebhook(hook.url, hook.secret, event, payload);
      await db.insert(adminWebhookDeliveries).values({
        id: crypto.randomUUID(),
        webhookId: hook.id,
        event,
        payload: payload as Record<string, unknown>,
        statusCode,
        success,
        attempts: 1,
        createdAt: new Date(),
      });
    })
  );
}
