import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { sendWebhook } from "@/lib/webhook";
import { requireApiAuth, handleApiError } from "@/lib/api-auth";

export async function POST() {
  try {
    await requireApiAuth();
    const settings = await prisma.appSettings.findUnique({
      where: { id: "singleton" },
    });

    if (!settings?.webhookUrl) {
      return NextResponse.json(
        { error: "Webhook URL is not configured" },
        { status: 400 }
      );
    }

    const testCard = {
      id: "test_123",
      name: "Test Card",
      email: "test@example.com",
      ocrStatus: "complete",
      reviewStatus: "unreviewed",
      ocrConfidence: 92,
    };

    const result = await sendWebhook(
      settings.webhookUrl,
      settings.webhookSecret,
      "test",
      testCard
    );

    if (result.ok) {
      return NextResponse.json({ ok: true, message: "Test webhook sent successfully" });
    } else {
      return NextResponse.json(
        { ok: false, error: result.error },
        { status: 400 }
      );
    }
  } catch (error) {
    return handleApiError(error);
  }
}
