import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { createNotification } from "@/lib/notifications";
import { logActivity } from "@/lib/activity-log";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";

export async function POST(req: NextRequest) {
  try {
    const session = await requireApiAuthWithOrg("cards.assign");
    const user = await prisma.user.findUniqueOrThrow({ where: { id: session.user.id } });

    const body = await req.json();
    const { cardIds, assignToUserId } = body as {
      cardIds: string[];
      assignToUserId: string;
    };

    if (!cardIds?.length || !assignToUserId) {
      return NextResponse.json(
        { error: "cardIds and assignToUserId are required" },
        { status: 400 }
      );
    }

    const assignee = await prisma.user.findUnique({
      where: { id: assignToUserId },
    });
    if (!assignee) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    await prisma.responseCard.updateMany({
      where: { id: { in: cardIds }, organizationId: session.user.orgId },
      data: {
        assignedToId: assignToUserId,
        assignedById: user.id,
        assignedAt: new Date(),
        reviewStatus: "assigned",
      },
    });

    for (const cardId of cardIds) {
      logActivity(
        cardId,
        "assignment",
        "user",
        `Assigned to ${assignee.displayName} by ${user.displayName}`,
        [{ field: "assignedToId", from: null, to: assignToUserId }],
        user.id
      ).catch(() => {});
    }

    await createNotification({
      type: "card_assigned",
      title: "Cards Assigned to You",
      message: `${cardIds.length} card(s) assigned by ${user.displayName}`,
      actionUrl: "/?assignedToId=me",
      userId: assignToUserId,
    });

    return NextResponse.json({
      ok: true,
      assigned: cardIds.length,
      assignee: assignee.displayName,
    });
  } catch (error) {
    return handleApiError(error);
  }
}
