import { HttpError } from "../middleware/errorHandler";
import { logActivity } from "./activity";
import { notifyUser } from "./notifications";
import { portalTicketCommented } from "./portalTicketMail";
import { prisma } from "./prisma";

type CommentCard = { id: string; boardId: string; title: string };

/** Creates a comment (text and/or voice note) and sends the same mention/follower
 * notifications for both kinds. Used by the comment routes and the AI assistant. */
export async function createCommentAndNotify(params: {
  card: CommentCard;
  authorId: string;
  bodyHtml: string;
  parentId?: string;
  /** Answering a reply: the new comment joins that reply's thread and remembers which reply it answers. */
  replyToId?: string;
  mentionUserIds?: string[];
  audio?: { url: string; mimeType: string; durationSec: number | null; sizeBytes: number };
}) {
  const { card, authorId } = params;
  let replyToId: string | undefined;
  if (params.replyToId) {
    const target = await prisma.comment.findUnique({ where: { id: params.replyToId } });
    if (!target || target.cardId !== card.id) {
      throw new HttpError(400, "The comment you are replying to was not found on this card");
    }
    replyToId = target.id;
    params = { ...params, parentId: target.parentId ?? target.id };
  }
  if (params.parentId) {
    const parent = await prisma.comment.findUnique({ where: { id: params.parentId } });
    if (!parent || parent.cardId !== card.id) {
      throw new HttpError(400, "Parent comment not found on this card");
    }
  }

  const comment = await prisma.comment.create({
    data: {
      cardId: card.id,
      authorId,
      bodyHtml: params.bodyHtml,
      parentId: params.parentId,
      replyToId,
      audioUrl: params.audio?.url,
      audioMimeType: params.audio?.mimeType,
      audioDurationSec: params.audio?.durationSec,
      audioSizeBytes: params.audio?.sizeBytes,
      mentions: params.mentionUserIds
        ? { create: params.mentionUserIds.map((userId) => ({ cardId: card.id, userId })) }
        : undefined,
    },
  });

  // Portal tickets: requester / chosen addresses get an update email (only when enabled in Portal settings)
  try {
    portalTicketCommented(card.id, comment.id, authorId, !!params.parentId);
  } catch (err) {
    console.error("[portal-mail] could not queue the comment update:", err);
  }

  await logActivity({
    boardId: card.boardId,
    cardId: card.id,
    actorId: authorId,
    action: "comment.created",
    metadata: { commentId: comment.id, ...(params.audio ? { voice: true } : {}) },
  });

  const author = await prisma.user.findUnique({ where: { id: authorId } });
  const who = author?.name ?? "Someone";

  for (const userId of params.mentionUserIds ?? []) {
    await notifyUser({
      recipientId: userId,
      actorId: authorId,
      type: "MENTION",
      message: `${who} mentioned you in "${card.title}"`,
      cardId: card.id,
      boardId: card.boardId,
    });
  }

  const followerIds = new Set<string>();
  const commenters = await prisma.comment.findMany({
    where: { cardId: card.id },
    select: { authorId: true },
    distinct: ["authorId"],
  });
  const members = await prisma.cardMember.findMany({
    where: { cardId: card.id },
    select: { userId: true },
  });
  for (const c of commenters) followerIds.add(c.authorId);
  for (const m of members) followerIds.add(m.userId);
  followerIds.delete(authorId);
  for (const mentioned of params.mentionUserIds ?? []) followerIds.delete(mentioned);

  for (const userId of followerIds) {
    await notifyUser({
      recipientId: userId,
      actorId: authorId,
      type: "COMMENT",
      message: params.audio ? `${who} left a voice comment on "${card.title}"` : `${who} commented on "${card.title}"`,
      cardId: card.id,
      boardId: card.boardId,
    });
  }

  return comment;
}
