'use client';

// ─────────────────────────────────────────────────────────────────────────────
// AuthContext — manages authentication state in memory
//
// Design decisions:
//  - accessToken is stored in React state (memory only — never localStorage)
//  - refreshToken lives in an httpOnly cookie (set by backend, never JS-readable)
//  - On mount, attempts a silent session restore via POST /auth/refresh
//  - Bridges token state to the api-client singleton via configureApiClient()
// ─────────────────────────────────────────────────────────────────────────────

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState,
} from 'react';
import { useRouter } from 'next/navigation';
import { configureApiClient, apiPost, apiGet } from '@/services/api-client';
import { buildAbility, nullAbility } from '@/utils/ability';
import type { User, Permission, AuthContextValue } from '@/types';
import type { AppAbility } from '@/utils/ability';

// ─────────────────────────────────────────────
// Context
// ─────────────────────────────────────────────

const AuthContext = createContext<AuthContextValue | null>(null);
const AbilityContext = createContext<AppAbility>(nullAbility);

// ─────────────────────────────────────────────
// Provider
// ─────────────────────────────────────────────

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const router = useRouter();

  const [user, setUser] = useState<User | null>(null);
  const [accessToken, setAccessTokenState] = useState<string | null>(null);
  const [activeRoleId, setActiveRoleId] = useState<number | null>(null);
  const [isLoading, setIsLoading] = useState(true); // true until session restore completes
  const [ability, setAbility] = useState<AppAbility>(nullAbility);

  // Ref so the api-client callback always has the latest token without closure stale issues
  const accessTokenRef = useRef<string | null>(null);

  const setAccessToken = useCallback((token: string | null) => {
    accessTokenRef.current = token;
    setAccessTokenState(token);
  }, []);

  // ─────────────────────────────────────────────
  // Wire up the api-client singleton once on mount.
  // This bridges the React state into the non-React api-client module.
  // ─────────────────────────────────────────────
  useEffect(() => {
    configureApiClient({
      getAccessToken: () => accessTokenRef.current,
      onTokenRefreshed: (newToken) => setAccessToken(newToken),
      onLogout: () => performLogout(),
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ─────────────────────────────────────────────
  // Load permissions and build CASL ability
  // ─────────────────────────────────────────────
  const loadAbility = useCallback(
    async (token: string, currentUser: User, roleId?: number | null) => {
      try {
        // Temporarily set token so apiFetch can attach it
        accessTokenRef.current = token;
        const url = roleId ? `/permissions?roleId=${roleId}` : '/permissions';
        const permissions = await apiGet<Permission[]>(url);
        const built = buildAbility(permissions, {
          ...currentUser,
          id: currentUser.id,
        });
        setAbility(built);
      } catch {
        // Non-critical — fall back to no permissions
        setAbility(nullAbility);
      }
    },
    [],
  );

  // ─────────────────────────────────────────────
  // Session restore on app mount
  // Calls POST /auth/refresh — the httpOnly cookie is sent automatically.
  // If valid → restore session silently. If invalid → stay logged out.
  // ─────────────────────────────────────────────
  const refreshSession = useCallback(async (): Promise<boolean> => {
    try {
      const data = await apiPost<{ accessToken: string; user?: User }>(
        '/auth/refresh',
        undefined,
        { auth: false }, // no Bearer token — cookie is the credential
      );

      if (!data.accessToken) return false;

      let restoredUser = data.user ?? null;

      // If user wasn't in the refresh response, fetch it separately
      if (!restoredUser && data.accessToken) {
        // Set token first so the request can be made authenticated
        accessTokenRef.current = data.accessToken;
        try {
          restoredUser = await apiGet<User>('/auth/me');
        } catch {
          // /auth/me might not exist — that's ok, user stays null
        }
      }

      setAccessToken(data.accessToken);
      setUser(restoredUser);

      if (restoredUser) {
        // Find default role
        const defaultRole = restoredUser.userRoles?.find((ur) => ur.isDefault);
        const initialRoleId = defaultRole?.roleId ?? null;
        setActiveRoleId(initialRoleId);
        await loadAbility(data.accessToken, restoredUser, initialRoleId);
      }

      return true;
    } catch {
      return false;
    }
  }, [setAccessToken, loadAbility]);

  // Run session restore once on mount
  useEffect(() => {
    refreshSession().finally(() => setIsLoading(false));
  }, [refreshSession]);

  // ─────────────────────────────────────────────
  // Login
  // ─────────────────────────────────────────────
  const login = useCallback(
    async (email: string, password: string) => {
      const data = await apiPost<{ accessToken: string; user: User }>(
        '/auth/login',
        { email, password },
        { auth: false }, // no token yet
      );

      setAccessToken(data.accessToken);
      setUser(data.user);

      if (data.user) {
        const defaultRole = data.user.userRoles?.find((ur) => ur.isDefault);
        const initialRoleId = defaultRole?.roleId ?? null;
        setActiveRoleId(initialRoleId);
        await loadAbility(data.accessToken, data.user, initialRoleId);
      }

      router.push('/dashboard');
    },
    [setAccessToken, loadAbility, router],
  );

  // ─────────────────────────────────────────────
  // Logout
  // ─────────────────────────────────────────────
  const performLogout = useCallback(async () => {
    try {
      await apiPost('/auth/logout');
    } catch {
      // Ignore errors — clear local state regardless
    } finally {
      setAccessToken(null);
      setUser(null);
      setActiveRoleId(null);
      setAbility(nullAbility);
      router.push('/login');
    }
  }, [setAccessToken, router]);

  const logout = performLogout;

  const switchRole = useCallback(
    async (roleId: number | null) => {
      if (!accessTokenRef.current || !user) return;
      setActiveRoleId(roleId);
      await loadAbility(accessTokenRef.current, user, roleId);
      router.push('/dashboard');
    },
    [user, loadAbility, router],
  );

  const updateUser = useCallback((updatedUser: User) => {
    setUser(updatedUser);
  }, []);

  // ─────────────────────────────────────────────
  // Context value
  // ─────────────────────────────────────────────
  const value: AuthContextValue = {
    user,
    accessToken,
    activeRoleId,
    isAuthenticated: !!accessToken && !!user,
    isLoading,
    login,
    logout,
    switchRole,
    refreshSession,
    setAccessToken,
    updateUser,
  };

  return (
    <AuthContext.Provider value={value}>
      <AbilityContext.Provider value={ability}>
        {children}
      </AbilityContext.Provider>
    </AuthContext.Provider>
  );
}

// ─────────────────────────────────────────────
// Hooks
// ─────────────────────────────────────────────

/** Returns the authentication context. Must be inside <AuthProvider>. */
export function useAuth(): AuthContextValue {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used inside <AuthProvider>');
  return ctx;
}

/** Returns the CASL ability for the current user. */
export function useAbility(): AppAbility {
  return useContext(AbilityContext);
}

/** Returns true if the current user can perform action on resource. */
export function useCan(action: string, resource: string): boolean {
  const ability = useAbility();
  return ability.can(action, resource);
}
