import { NextResponse } from "next/server";
import crypto from "crypto";
import { prisma } from "@/lib/prisma";

export async function POST(request: Request) {
  const payload = await request.text();
  if (process.env.STRIPE_WEBHOOK_SECRET && !verifyStripeSignature(payload, request.headers.get("stripe-signature"))) {
    return NextResponse.json({ ok: false, error: "Invalid webhook signature." }, { status: 400 });
  }

  const event = JSON.parse(payload) as {
    id?: string;
    type?: string;
    data?: { object?: Record<string, unknown> };
  };
  const object = event.data?.object ?? {};
  const metadata = (object.metadata ?? {}) as Record<string, string>;
  const userId = metadata.userId || undefined;
  const type = event.type ?? "unknown";

  await prisma.billingEvent.create({
    data: {
      userId,
      providerEventId: event.id,
      eventType: type,
      status: "received",
      payload,
    },
  }).catch(() => null);

  if (userId && (type === "checkout.session.completed" || type === "customer.subscription.updated" || type === "customer.subscription.created")) {
    const periodEndRaw = Number(object.current_period_end ?? object.expires_at ?? 0);
    const premiumUntil = periodEndRaw ? new Date(periodEndRaw * 1000) : new Date(Date.now() + 1000 * 60 * 60 * 24 * 31);
    await prisma.user.update({
      where: { id: userId },
      data: { premiumStatus: "active", premiumUntil },
    });
    await prisma.premiumSubscription.upsert({
      where: { id: String(object.subscription ?? object.id ?? event.id) },
      update: { status: "active", currentPeriodEnd: premiumUntil },
      create: {
        id: String(object.subscription ?? object.id ?? event.id),
        userId,
        plan: metadata.plan ?? "monthly",
        status: "active",
        providerSubscriptionId: String(object.subscription ?? object.id ?? ""),
        currentPeriodEnd: premiumUntil,
      },
    });
  }

  if (userId && (type === "customer.subscription.deleted" || type === "invoice.payment_failed")) {
    await prisma.user.update({ where: { id: userId }, data: { premiumStatus: "past_due" } });
  }

  return NextResponse.json({ received: true });
}

function verifyStripeSignature(payload: string, header: string | null) {
  if (!header || !process.env.STRIPE_WEBHOOK_SECRET) return false;
  const parts = Object.fromEntries(
    header.split(",").map((part) => {
      const [key, value] = part.split("=");
      return [key, value];
    })
  );
  const timestamp = parts.t;
  const signature = parts.v1;
  if (!timestamp || !signature) return false;

  const signedPayload = `${timestamp}.${payload}`;
  const expected = crypto
    .createHmac("sha256", process.env.STRIPE_WEBHOOK_SECRET)
    .update(signedPayload, "utf8")
    .digest("hex");

  try {
    return crypto.timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(signature, "hex"));
  } catch {
    return false;
  }
}
