'use server'

import { prisma, pwd_key_config } from "@/module/_global";
import { unsealData } from "iron-session";
import { cookies } from "next/headers";

export default async function funGetUserByCookies() {
   const sessionCookie = cookies().get("sessionCookieSDM")

   if (sessionCookie != undefined) {
      const userId: any = await unsealData(sessionCookie.value, {
         password: pwd_key_config,
      });

      const user = await prisma.user.findUnique({
         where: {
            id: userId.user ? String(userId.user) : String(userId),
         },
      });

      const village = await prisma.village.findUnique({
         where: {
            id: user?.idVillage
         }
      })

      const warna = await prisma.colorTheme.findUnique({
         where: {
            id: String(village?.idTheme)
         }
      })

      return {
         id: user?.id,
         idUserRole: user?.idUserRole,
         name: user?.name,
         idVillage: user?.idVillage,
         idGroup: user?.idGroup,
         idPosition: user?.idPosition,
         theme: warna,
         showNotification: userId?.showNotification
      };
   }else{
      return {
         id: undefined,
         idUserRole: undefined,
         name: undefined,
         idVillage: undefined,
         idGroup: undefined,
         idPosition: undefined,
         theme: undefined,
         showNotification: undefined
      };
   }

}