import { NextResponse } from "next/server";

import { verifyAndParsePolarWebhook } from "@/lib/payments/polar";
import { activatePlanInDb, deactivatePlanInDb } from "@/lib/appwrite/subscription-actions";
import type { TenantPlan } from "@/lib/appwrite/schema";

export async function POST(req: Request): Promise<NextResponse> {
  const rawBody = await req.text();
  const headers: Record<string, string> = {};
  req.headers.forEach((v, k) => { headers[k] = v; });

  let event;
  try {
    event = verifyAndParsePolarWebhook(headers, rawBody);
  } catch {
    return new NextResponse("Webhook imzası geçersiz.", { status: 400 });
  }

  try {
    if (event.type === "order.created" || event.type === "subscription.active") {
      const tenantId = (event.data as { metadata?: Record<string, string> }).metadata?.tenant_id;
      if (!tenantId) {
        return new NextResponse("tenant_id metadata eksik.", { status: 400 });
      }
      await activatePlanInDb(tenantId, "pro" as TenantPlan, "polar");
    }

    if (event.type === "subscription.canceled" || event.type === "subscription.revoked") {
      const tenantId = (event.data as { metadata?: Record<string, string> }).metadata?.tenant_id;
      if (tenantId) {
        await deactivatePlanInDb(tenantId);
      }
    }
  } catch (e) {
    console.error("[polar-webhook]", e);
    return new NextResponse("İşlem hatası.", { status: 500 });
  }

  return new NextResponse("OK", { status: 200 });
}
