import { usePathname, useRouter } from 'expo-router';
import { useCallback } from 'react';

import { useAppSelector } from '@/hooks/redux';

type RedirectParams = Record<string, string | number | boolean | undefined>;

type EnsureOptions = {
  redirectTo?: string;
  redirectParams?: RedirectParams;
};

export function useAuthGuard() {
  const router = useRouter();
  const currentPath = usePathname();
  const token = useAppSelector((s) => (s as any)?.user?.token as string | null);
  const isLoggedIn = !!token;

  const ensureLoggedIn = useCallback(async (options?: EnsureOptions): Promise<boolean> => {
    if (isLoggedIn) return true;

    const redirectTo = options?.redirectTo ?? currentPath ?? '/(tabs)';
    const paramsJson = options?.redirectParams ? JSON.stringify(options.redirectParams) : undefined;

    router.push({
      pathname: '/auth/login',
      params: {
        redirectTo,
        ...(paramsJson ? { redirectParams: paramsJson } : {}),
      },
    } as any);
    return false;
  }, [isLoggedIn, router, currentPath]);

  const pushIfAuthedElseLogin = useCallback((pathname: string, params?: RedirectParams) => {
    if (isLoggedIn) {
      router.push({ pathname, params } as any);
      return;
    }
    const paramsJson = params ? JSON.stringify(params) : undefined;
    router.push({ pathname: '/auth/login', params: { redirectTo: pathname, ...(paramsJson ? { redirectParams: paramsJson } : {}) } } as any);
  }, [isLoggedIn, router]);

  const guardHandler = useCallback(
    <T extends any[]>(fn: (...args: T) => any | Promise<any>, options?: EnsureOptions) => {
      return async (...args: T) => {
        const ok = await ensureLoggedIn(options);
        if (!ok) return;
        return fn(...args);
      };
    },
    [ensureLoggedIn]
  );

  return {
    isLoggedIn,
    ensureLoggedIn,
    pushIfAuthedElseLogin,
    guardHandler,
  } as const;
}


