import type { APIEvent } from "@solidjs/start/server";
import { stripe } from "~/server/stripe";
import { handleWebhookEvent } from "~/server/services/billing.service";

export async function POST(event: APIEvent) {
  const body = await event.request.text();
  const signature = event.request.headers.get("stripe-signature");

  if (!signature) {
    return new Response("Missing stripe-signature header", { status: 400 });
  }

  try {
    const webhookEvent = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET ?? "",
    );

    await handleWebhookEvent(webhookEvent);

    return new Response("OK", { status: 200 });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Webhook error";
    return new Response(message, { status: 400 });
  }
}
