import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { readItem, mapItemToCardFields } from "@/lib/monday";
import { logActivity, diffCardFields } from "@/lib/activity-log";
import { createNotification } from "@/lib/notifications";

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    if (body.challenge) {
      return NextResponse.json({ challenge: body.challenge });
    }

    const event = body.event;
    if (!event) {
      return NextResponse.json({ ok: true });
    }

    const itemId = String(event.pulseId || event.itemId || "");
    if (!itemId) {
      return NextResponse.json({ ok: true });
    }

    const card = await prisma.responseCard.findFirst({
      where: { mondayItemId: itemId },
    });
    if (!card) {
      return NextResponse.json({ ok: true });
    }

    const settings = await prisma.appSettings.findUnique({
      where: { id: "singleton" },
    });
    if (!settings?.mondayApiToken) {
      return NextResponse.json({ ok: true });
    }

    const mondayItem = await readItem(settings.mondayApiToken, itemId);
    if (!mondayItem) {
      return NextResponse.json({ ok: true });
    }

    const columnMap = (settings.mondayColumnMap as Record<string, string>) ?? {};
    const cardFields = mapItemToCardFields(mondayItem.columnValues, columnMap);

    if (Object.keys(cardFields).length === 0) {
      return NextResponse.json({ ok: true });
    }

    const oldCard = card as unknown as Record<string, unknown>;
    const data: Record<string, unknown> = {};
    for (const [key, val] of Object.entries(cardFields)) {
      data[key] = val;
    }

    const updated = await prisma.responseCard.update({
      where: { id: card.id },
      data: data as Parameters<typeof prisma.responseCard.update>[0]["data"],
    });

    const newCard = updated as unknown as Record<string, unknown>;
    const changes = diffCardFields(oldCard, newCard);
    if (changes.length > 0) {
      await logActivity(card.id, "monday_sync", "monday.com",
        `${changes.length} field(s) synced from Monday.com`, changes);

      await createNotification({
        type: "monday_sync",
        title: "Monday.com Sync",
        message: `${changes.length} field(s) updated for ${card.name || "Unnamed Card"}`,
        cardId: card.id,
        actionUrl: `/cards/${card.id}`,
      });
    }

    return NextResponse.json({ ok: true });
  } catch (error) {
    console.error("[monday/webhook POST]", error);
    return NextResponse.json({ ok: true });
  }
}
