"use server";
import { cookies } from "next/headers";

const isSecure = process.env?.NEXT_PUBLIC_IS_SECURED == "true";

export async function createToken(token, refreshToken) {
   cookies().set({
      name: "token",
      value: token,
      maxAge: 60 * 60 * 24 * 5,
      secure: isSecure,
      httpOnly: true
   });
   if (!refreshToken) return;
   cookies().set({
      name: "refresh_token",
      value: refreshToken,
      secure: isSecure,
      maxAge: 60 * 60 * 24 * 30,
      httpOnly: true
   });
}


export async function getToken() {
   const cookStore = await cookies()
   const token = cookStore.get("token")?.value;
   if (!token) {
      return null;
   }
   return token;
}

export async function deleteToken() {
   cookies().delete("token");
   cookies().delete("refresh_token");
}

// function to create vendors permissions 
export async function createVendor(vendor) {
   cookies().set({
      name: "vendor",
      value: vendor,
      secure: isSecure,
      httpOnly: true
   });
}

//  function to get vendor permissions
export async function getVendor() {
   const vendor = cookies().get("vendor")?.value;
   if (vendor == "1") {
      return true;
   }
   return false;
}

export async function setUserPermissions(data) {
   cookies().set({
      name: "UD",
      value: JSON.stringify(data),
      maxAge: 60 * 60 * 24 * 30,
      secure: isSecure,
      httpOnly: true
   });
}
export async function getUserPermissions() {
   return cookies().get("UD")?.value;
}
export async function setSiteSettings(data) {
   cookies().set({
      name: "STT",
      value: JSON.stringify(data),
      secure: isSecure,
      httpOnly: true
   });
}
export async function getSiteSettings() {
   return cookies().get("STT")?.value;
}