import { objectFilterEmpty, objecthasKey, spliceObject } from "@/utils/library";
import { NextResponse } from "next/server";
import { v6 as uuid } from "uuid";
import { JWT } from "@/utils/jwt";
import { increasePostView } from "@/models/posts.model";
import { getPostBySlug } from "@/services/posts";
import { increaseAnalytics } from "@/models/analytics";

export async function postViewCounting(request) {
  let data = {};
  const MAX_AGE = 60 * 60 * 12;
  const jwt = new JWT();
  const response = NextResponse.next();
  const cookies = Object.fromEntries(
    request.cookies.getAll().map((c) => Object.values(c))
  );
  const isAdmin = !!cookies.accessToken || !!cookies.refreshToken;
  const isAnonim = objecthasKey(cookies, "_anon");
  const currentSlug = request.nextUrl.pathname.split("/").slice(-1)[0];

  const currentPost = await getPostBySlug(currentSlug);
  if (!currentPost) return response;

  if (isAdmin) return response;
  if (isAnonim)
    data = spliceObject(jwt.decodeToken(cookies._anon), [
      "id",
      "current",
    ]).selected;
  else data = { id: uuid(), current: [] };

  if (!data.current.includes(currentSlug)) {
    data.current.push(currentSlug);

    await increasePostView(currentSlug);
    await increaseAnalytics(data.id);
    setCookie(
      response,
      "_anon",
      jwt.encodeSomething(data, MAX_AGE),
      isAnonim ? null : MAX_AGE
    );
  }

  return response;
}

const setCookie = (response, key, value, maxAge = null) => {
  response.cookies.set(
    key,
    value,
    objectFilterEmpty({
      httpOnly: true,
      sameSite: "strict",
      path: "/",
      maxAge,
    })
  );
};
