import {getTimetoMilis, timestampToDate} from "~/utils/helper";
import {signOut} from "next-auth/react";

export default defineNuxtRouteMiddleware(async (to, from) => {
  if (process.server) return;
  try {
    const sess = await useSessionLogin('getSess');
    console.log('session data:', sess);
    // console.log('route auth requirement:', timestampToDate(sess?.expires_in?.timestamps, 'id-ID'));
    // const timeMilis= sess?.expires_in?.timestamps*1000
    // console.log(timeMilis)
    // console.log('route auth requirement:', new Date(timeMilis));
    // console.log('milis:', timestampToDate(sess?.expires_in?.timestamps,'id-ID'));
    // console.log('milis:', timestampToDate(getTimetoMilis(),'id-ID'));

    // Jika session tidak ada atau sudah expired

    if(!sess || getTimetoMilis()>= sess?.user_payload?.expires?.expires_at){
      if(to.path!=='/auth/login'){
        await signOut()
        return navigateTo({
          path: "/auth/login",
          query: {
            ...to.query,
            reason: "auth_required",
            continue: "true"
          }
        });
      }
      return;
    }


    // Optional: Pengecekan tipe user jika diperlukan
    // if (to.meta.auth && to.meta.auth !== sess?.user_payload?.typeUser) {
    const metaRoles=to.meta?.roles;
    console.log(metaRoles);
    if (!to.meta || !metaRoles.includes(sess?.user_payload?.typeUser)) {
      return navigateTo('/auth/401');
    }

  } catch (err) {
    console.error('Session check failed:', err);
    if (to.path !== '/auth/login') {
      return navigateTo({
        path: '/auth/login',
        query: {
          returnUrl: to.fullPath,
          reason: 'session check failed'
        }
      });
    }
  }
});
