import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { fireIntegrationEvent } from "@/lib/integrations";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";

export async function POST(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithOrg("cards.edit");
    const { id } = await params;
    const card = await prisma.responseCard.findUnique({
      where: { id },
    });

    if (!card || card.organizationId !== session.user.orgId) {
      return NextResponse.json({ error: "Card not found" }, { status: 404 });
    }

    const updated = await prisma.responseCard.update({
      where: { id },
      data: { reviewStatus: "exported" },
    });

    fireIntegrationEvent("card_exported", id, {
      oldCard: card as unknown as Record<string, unknown>,
    }).catch(() => {});

    return NextResponse.json(updated);
  } catch (error) {
    return handleApiError(error);
  }
}
