import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { createWebhookSubscription, deleteWebhookSubscription } from "@/lib/monday";
import { requireApiAuth, handleApiError } from "@/lib/api-auth";

export async function POST(request: NextRequest) {
  try {
    await requireApiAuth();
    const body = await request.json().catch(() => ({}));
    const action = body.action as string;

    const settings = await prisma.appSettings.findUnique({
      where: { id: "singleton" },
    });
    if (!settings?.mondayApiToken || !settings?.mondayBoardId) {
      return NextResponse.json(
        { error: "Monday.com API token and board ID are required" },
        { status: 400 }
      );
    }

    if (action === "subscribe") {
      const callbackUrl = String(body.callbackUrl || settings.mondayWebhookUrl || "");
      if (!callbackUrl) {
        return NextResponse.json(
          { error: "Callback URL is required" },
          { status: 400 }
        );
      }

      if (settings.mondayWebhookId) {
        try {
          await deleteWebhookSubscription(settings.mondayApiToken, settings.mondayWebhookId);
        } catch { /* old webhook may not exist */ }
      }

      const webhookId = await createWebhookSubscription(
        settings.mondayApiToken,
        settings.mondayBoardId,
        callbackUrl
      );

      await prisma.appSettings.update({
        where: { id: "singleton" },
        data: { mondayWebhookId: webhookId, mondayWebhookUrl: callbackUrl },
      });

      return NextResponse.json({ subscribed: true, webhookId });
    } else if (action === "unsubscribe") {
      if (settings.mondayWebhookId) {
        try {
          await deleteWebhookSubscription(settings.mondayApiToken, settings.mondayWebhookId);
        } catch { /* may already be deleted */ }
      }

      await prisma.appSettings.update({
        where: { id: "singleton" },
        data: { mondayWebhookId: "", mondayWebhookUrl: "" },
      });

      return NextResponse.json({ subscribed: false });
    }

    return NextResponse.json({ error: "Invalid action" }, { status: 400 });
  } catch (error) {
    return handleApiError(error);
  }
}
