"use server";

import { JWT } from "@/utils/jwt";
import { cookies } from "next/headers";

export const getCookies = async () => {
  const result = await cookies();
  return result.getAll();
};

export const removeCookie = async (name) => {
  const cookie = await cookies();
  const currentCookie = cookie.get(name)?.value;
  if (!currentCookie) return;
  cookie.delete(name);
};

export const removeTokenCookies = async () => {
  await removeCookie("accessToken");
  await removeCookie("refreshToken");
};

export const decodeAnonymous = async () => {
  try {
    const cookie = await cookies();
    const accessToken = cookie.get("_anon")?.value;

    if (!accessToken) return null;

    const jwt = new JWT();
    return {
      value: accessToken,
      data: jwt.decodeToken(accessToken),
    };
  } catch (error) {
    return null;
  }
};

export const decodeAccessToken = async () => {
  try {
    const cookie = await cookies();
    const accessToken = cookie.get("accessToken")?.value;

    if (!accessToken) return null;

    const jwt = new JWT();
    return {
      value: accessToken,
      data: jwt.decodeToken(accessToken),
    };
  } catch (error) {
    return null;
  }
};

export const decodeRefreshToken = async () => {
  const cookie = await cookies();
  const refreshToken = cookie.get("refreshToken")?.value;

  if (!refreshToken) return null;

  const jwt = new JWT();
  return {
    value: refreshToken,
    data: jwt.verifyToken({ refresh: refreshToken }),
  };
};

export const getCookieByName = async (name) => {
  const cookie = await cookies();
  return cookie.get(name)?.value;
};

export const setCookie = async (name, value, options) => {
  const cookie = await cookies();
  cookie.set(name, value, options);
};
