import { PropsWithChildren, createContext, useEffect, useState } from "react";
import { IAuthService } from "../services";

export type AuthContextType = {
  token: string | null;
  isAuthenticated: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
};

export interface AuthContextParams {
  authService: IAuthService;
  getAccessToken: () => string | null;
  setAccessToken: (token: string) => void;
  clearAccessToken: () => void;
}

export const AuthContext = createContext<AuthContextType | undefined>(undefined);

/**
 * Proveedor de autenticación para toda la app.
 */
export const AuthProvider = ({
  params,
  children,
}: PropsWithChildren<{ params: AuthContextParams }>) => {
  const { getAccessToken, setAccessToken, clearAccessToken, authService } = params;

  const [token, setToken] = useState<string | null>(getAccessToken());

  useEffect(() => {
    setToken(getAccessToken());
  }, []);

  const login = async (email: string, password: string) => {
    const { token } = await authService.login({ email, password });
    setAccessToken(token);
    setToken(token);
  };

  const logout = () => {
    clearAccessToken();
    setToken(null);
  };

  return (
    <AuthContext.Provider value={{ token, isAuthenticated: !!token, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};
