import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/admin/db";

export const dynamic = "force-dynamic";

/**
 * POST /api/push/subscribe
 * Save or update a Web Push subscription from a blog reader's browser.
 * Public — no admin authentication required (readers opt in voluntarily).
 */
export async function POST(req: NextRequest) {
  try {
    const body = await req.json().catch(() => null);

    if (
      !body ||
      typeof body.endpoint !== "string" ||
      !body.keys ||
      typeof body.keys.p256dh !== "string" ||
      typeof body.keys.auth !== "string"
    ) {
      return NextResponse.json(
        { error: "Invalid push subscription payload." },
        { status: 400 }
      );
    }

    const userAgent = req.headers.get("user-agent") || null;

    await db.savePushSubscription({
      endpoint: body.endpoint,
      keys: {
        p256dh: body.keys.p256dh,
        auth: body.keys.auth,
      },
      userAgent,
    });

    return NextResponse.json({ ok: true }, { status: 201 });
  } catch (err: any) {
    console.error("[POST /api/push/subscribe]", err);
    return NextResponse.json(
      { error: "Failed to save push subscription." },
      { status: 500 }
    );
  }
}

/**
 * DELETE /api/push/subscribe
 * Remove a Web Push subscription (user opted out).
 */
export async function DELETE(req: NextRequest) {
  try {
    const body = await req.json().catch(() => null);

    if (!body || typeof body.endpoint !== "string") {
      return NextResponse.json(
        { error: "endpoint is required." },
        { status: 400 }
      );
    }

    await db.deletePushSubscription(body.endpoint);

    return NextResponse.json({ ok: true });
  } catch (err: any) {
    console.error("[DELETE /api/push/subscribe]", err);
    return NextResponse.json(
      { error: "Failed to remove push subscription." },
      { status: 500 }
    );
  }
}
