import { WebhookVerificationError } from "@polar-sh/sdk/webhooks";
import { processPolarWebhook } from "@/lib/polar-billing";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function POST(request: Request) {
  const body = await request.text();

  try {
    const result = await processPolarWebhook({ body, headers: request.headers });
    return Response.json({ ok: true, ...result });
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return Response.json(
        { error: "invalid-webhook-signature" },
        { status: 403 },
      );
    }

    console.error(
      "[polar-webhook] processing failed",
      error instanceof Error ? error.message : error,
    );
    return Response.json(
      { error: "polar-webhook-processing-failed" },
      { status: 500 },
    );
  }
}
