import { HttpError } from "../middleware/errorHandler";
import { logActivity } from "./activity";
import { positionBetween } from "./position";
import { prisma } from "./prisma";
import { emitToBoard } from "./socketBus";

// A CardLink shows one card on another board as well as its home board. It's
// the same card everywhere (title, description, members, comments, custom field
// values...), so editing it anywhere updates it everywhere; each linked board
// only keeps its own place for it (list + position).

export const cardLinkInclude = {
  board: { select: { id: true, name: true, workspace: { select: { id: true, name: true } } } },
  list: { select: { id: true, name: true } },
};

/** For a card query's `include`: `links: cardLinksInclude`. */
export const cardLinksInclude = {
  include: cardLinkInclude,
  orderBy: { createdAt: "asc" as const },
};

/** The card's home board plus every board it's linked into. Subitems follow
 * their parent's links. */
export async function cardBoardIds(card: { id: string; boardId: string; parentCardId?: string | null }) {
  const links = await prisma.cardLink.findMany({
    where: { cardId: { in: [card.id, ...(card.parentCardId ? [card.parentCardId] : [])] } },
    select: { boardId: true },
  });
  return [...new Set([card.boardId, ...links.map((l) => l.boardId)])];
}

/** Next position at the end of a list that can hold both its own cards and
 * cards linked in from other boards (they share one ordering). */
export async function endOfListPosition(listId: string): Promise<number> {
  const [lastCard, lastLink] = await Promise.all([
    prisma.card.findFirst({
      where: { listId, isArchived: false, parentCardId: null },
      orderBy: { position: "desc" },
      select: { position: true },
    }),
    prisma.cardLink.findFirst({ where: { listId }, orderBy: { position: "desc" }, select: { position: true } }),
  ]);
  const positions = [lastCard?.position, lastLink?.position].filter((p): p is number => typeof p === "number");
  return positionBetween(positions.length ? Math.max(...positions) : undefined, undefined);
}

/** Shows `cardId` on `boardId` in `listId` (or moves it there if it's already
 * linked to that board). Callers do the permission checks. */
export async function linkCardToBoard(params: { cardId: string; boardId: string; listId: string; actorId: string }) {
  const card = await prisma.card.findUnique({ where: { id: params.cardId } });
  if (!card) throw new HttpError(404, "Card not found");
  if (card.parentCardId) throw new HttpError(400, "Subitems can't be linked on their own; link the parent card instead");
  if (card.boardId === params.boardId) throw new HttpError(400, "The card already lives on this board");
  const list = await prisma.list.findUnique({ where: { id: params.listId } });
  if (!list || list.boardId !== params.boardId || list.isArchived) throw new HttpError(400, "List not found on that board");

  const existing = await prisma.cardLink.findUnique({
    where: { cardId_boardId: { cardId: params.cardId, boardId: params.boardId } },
  });
  if (existing && existing.listId === params.listId) {
    return prisma.cardLink.findUniqueOrThrow({ where: { id: existing.id }, include: cardLinkInclude });
  }

  const position = await endOfListPosition(params.listId);
  const link = existing
    ? await prisma.cardLink.update({
        where: { id: existing.id },
        data: { listId: params.listId, position },
        include: cardLinkInclude,
      })
    : await prisma.cardLink.create({
        data: {
          cardId: params.cardId,
          boardId: params.boardId,
          listId: params.listId,
          position,
          createdById: params.actorId,
        },
        include: cardLinkInclude,
      });

  if (!existing) {
    await logActivity({
      boardId: card.boardId,
      cardId: card.id,
      actorId: params.actorId,
      action: "card.linked",
      metadata: { boardId: params.boardId, boardName: link.board.name, listName: link.list.name },
    });
  }
  emitToBoard(params.boardId, "board:changed", {});
  emitToBoard(card.boardId, "board:changed", {});
  return link;
}
