import { RouteGuard, GuardResult } from "@sirou/core";
import { useAuthStore } from "./auth-store";

/**
 * Authentication Guard
 * Prevents unauthenticated users from accessing protected routes.
 */
export const authGuard: RouteGuard = {
  name: "auth",
  execute: async ({ route, meta }): Promise<GuardResult> => {
    const { isAuthenticated } = useAuthStore.getState();
    const requiresAuth = meta?.requiresAuth ?? false;

    console.log(
      `[AUTH_GUARD] checking: "${route}" (requiresAuth: ${requiresAuth}, auth: ${isAuthenticated})`,
    );

    if (requiresAuth && !isAuthenticated) {
      console.log(`[AUTH_GUARD] DENIED -> redirect /login`);
      return {
        allowed: false,
        redirect: "/login",
      };
    }

    return { allowed: true };
  },
};

export const guestGuard: RouteGuard = {
  name: "guest",
  execute: async ({ meta }): Promise<GuardResult> => {
    const { isAuthenticated } = useAuthStore.getState();
    const guestOnly = meta?.guestOnly ?? false;

    if (guestOnly && isAuthenticated) {
      console.log(`[GUEST_GUARD] Authenticated user blocked -> redirect /`);
      return {
        allowed: false,
        redirect: "/",
      };
    }

    return { allowed: true };
  },
};
