
"use server";

import { cookies } from "next/headers";
import { serialize } from "cookie";

import { jwtDecode } from "jwt-decode";
import { redirect } from "next/navigation";


const MAX_AGE = 60 * 60 * 24 * 30; // days;


export const setAuthCookie = (token: string, name: string) => {
  // const decoded: any = jwtDecode(token);
  

  const toBase64 = Buffer.from(token).toString("base64");

  cookies().set(name, toBase64, {
    httpOnly: true,
  });

  serialize(name, token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    maxAge: MAX_AGE,
    path: "/",
  });
};

const getAuthCookie = (name: string) => {
  //   const cookie = getCookie(name);



  const cookie = cookies().get(name);


  if (!cookie) return undefined;

  return Buffer.from(cookie.value, "base64").toString("ascii");
};

export const getValidAuthTokens = () => {
  const token = getAuthCookie("pharma_token");

  if (!token) return { token: null, decoded: null };
  const decoded = jwtDecode(token);
  
  // console.log("-------------- DECODED TOKEN -----")
  // console.log(decoded);

  return {
    token,
    decoded,
  };
};

export const logout = () => {
  cookies().delete("pharma_token");
  redirect(`/`);
};