import { parseToObjectId } from "@/models/helper";
import { addLockPost, getLockPostByUid } from "@/models/posts.model";
import { JWT } from "@/utils/jwt";
import { v6 as uuid } from "uuid";

export const postBeingEditing = async (request, response, accessToken) => {
  const jwt = new JWT();
  const data = jwt.decodeToken(accessToken) || {};
  const path = request.nextUrl.pathname;
  const isPostEditor = isPostEditorPage(path);
  const uid = uuid();
  const lockPostCookie = request.cookies.get("lockPost")?.value;

  if (!isPostEditor) return response;

  const post_id = path.split("/").pop();

  // check if post is already locked
  if (lockPostCookie) {
    const currentLockPost = await getLockPostByUid(lockPostCookie);
    const currentPost = currentLockPost.find(
      (item) => item.post_id === post_id
    );

    // if post is already locked
    if (currentPost) return response;
  }

  const lockData = {
    post_id,
    user_id: data._id,
    uid,
    heartBeat: new Date(),
    lockedSince: new Date(),
  };
  const lockPost = parseToObjectId(lockData, ["post_id", "user_id"]);

  // add to database
  await addLockPost(lockPost);

  // add lockpost to posts maintain
  response.cookies.set({
    name: "lockPost",
    value: uid,
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    path: "/",
  });

  return response;
};

const isPostEditorPage = (path) =>
  path.startsWith("/dashboard/posts/") &&
  path?.split("/")?.filter((item) => item)?.length === 3;
