/**
 * POST /api/integrations/notify-me
 * ---------------------------------
 * Records that a user wants to be notified when a specific integration
 * becomes available. Stored as a Notification row with channel="integration_request"
 * so it can be queried later to email interested users.
 */

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

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null);
  const brandId = body?.brandId as string | undefined;
  const integrationId = body?.integrationId as string | undefined;
  if (!brandId || !integrationId) {
    return NextResponse.json({ error: "brandId and integrationId required" }, { status: 400 });
  }

  // Permission check
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  try {
    await prisma.notification.create({
      data: {
        brandId,
        userId: user.id,
        title: `Integration request: ${integrationId}`,
        message: `User requested notification when ${integrationId} integration is available.`,
        type: "info",
        severity: "low",
        channel: "integration_request",
        metadata: { integrationId },
      },
    });
  } catch {
    // Best-effort — don't fail the request if notification insert fails
  }

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