import {
  doModifyComment as dbModifyComment,
  getComments as dbGetComments,
  getLatestComments as dbGetLatestComments,
  postComment as dbPostComment,
  wipeComment as dbWipeComment,
} from "@/app/www/system/DB";
import { CommentItem } from "@/app/www/type/CommentItem";
import { getDatetime } from "taehui-lib/date";

export const getComments = async (essayID: number) => {
  const comments = await dbGetComments(essayID);
  const data = new Map<number, CommentItem>();
  const commentItems = new Map<number, CommentItem>();

  comments.forEach(({ targetCommentID, commentID, ...comment }) => {
    const commentItem: CommentItem = {
      commentID,
      ...comment,
      comments: [],
    };
    if (targetCommentID !== -1) {
      data.get(targetCommentID)?.comments?.push(commentItem);
    } else {
      commentItems.set(commentID, commentItem);
    }
    data.set(commentID, commentItem);
  });

  return Array.from(commentItems.values());
};

export const postComment = async (
  targetCommentID: number,
  essayID: number,
  avatarID: string,
  level: number,
  text: string,
) => {
  return (
    1 <= level &&
    !!text &&
    dbPostComment(targetCommentID, essayID, avatarID, getDatetime(), text)
  );
};

export const doModifyComment = async (
  commentID: number,
  avatarID: string,
  text: string,
  level: number,
) => {
  return !!text && dbModifyComment(commentID, avatarID, text, level);
};

export const wipeComment = async (
  commentID: number,
  avatarID: string,
  level: number,
) => {
  return dbWipeComment(commentID, avatarID, level);
};

export const getLatestComments = async () => {
  return dbGetLatestComments();
};
