import { readMessengerMiniAppStartPath } from '~/composables/useMessengerMiniAppStart';

export default defineNuxtRouteMiddleware((to) => {
  const config = useRuntimeConfig();
  const authCookieName = config.public.authCookieName || 'fregat_auth_token';
  const authToken = useCookie<string | null>(authCookieName);

  const isLoginPage = to.path === '/login';
  const loginToken = typeof to.query.login_token === 'string' ? to.query.login_token.trim() : '';
  const miniAppStartPath = readMessengerMiniAppStartPath();
  const nextPath = miniAppStartPath || (to.fullPath.startsWith('/') ? to.fullPath : '/');

  if (!authToken.value && !isLoginPage) {
    return navigateTo({
      path: '/login',
      query: {
        next: nextPath,
      },
    });
  }

  if (authToken.value && isLoginPage && !loginToken) {
    const requestedNextPath = typeof to.query.next === 'string' && to.query.next.startsWith('/')
      ? to.query.next
      : miniAppStartPath || '/';
    return navigateTo(requestedNextPath);
  }

  if (authToken.value && to.path === '/' && miniAppStartPath && miniAppStartPath !== '/') {
    return navigateTo(miniAppStartPath);
  }
});
