'use client'
import {
  login
} from "./chunk-GMPQV5TL.mjs";
import {
  m2mAuthTokenApi
} from "./chunk-5FHEMJGG.mjs";

// src/storage/useM2mAuth.tsx
import { fetcher } from "matsuri-hooks";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState
} from "react";
import { jsx } from "react/jsx-runtime";
var AuthenticationContext = createContext(
  void 0
);
var checkJwtExpiration = (jwt) => {
  const splitted = jwt.split(".");
  if (splitted.length !== 3)
    return false;
  const [, payload] = splitted;
  const parsedPayload = JSON.parse(atob(payload));
  return /* @__PURE__ */ new Date() < new Date(parsedPayload.exp * 1e3);
};
var M2mAuthenticationProvider = ({
  children
}) => {
  var _a;
  const [token, setToken] = useState((_a = m2mAuthTokenApi.getCache()) != null ? _a : "");
  const authenticated = useMemo(() => !!token, [token]);
  const tryCheckAuth = useCallback(async () => {
    const authToken = await m2mAuthTokenApi.get();
    if (!(authToken && checkJwtExpiration(authToken))) {
      void m2mAuthTokenApi.clear();
      setToken("");
    } else {
      void m2mAuthTokenApi.set(authToken);
      setToken(authToken);
    }
  }, []);
  useEffect(() => {
    void tryCheckAuth();
  }, [tryCheckAuth]);
  const login2 = useCallback(async (input) => {
    const { data, error } = await fetcher(login(), {
      method: "POST",
      body: JSON.stringify(input)
    });
    if (data) {
      const authToken = data.accessToken;
      void m2mAuthTokenApi.set(authToken);
      setToken(authToken);
    }
    return {
      error,
      token: data ? data.accessToken : void 0
    };
  }, []);
  const logout = useCallback(() => {
    void m2mAuthTokenApi.clear();
    window.location.reload();
  }, []);
  const updateToken = useCallback(async (token2) => {
    if (checkJwtExpiration(token2)) {
      return {
        error: new Error("M2MAuthToken is expired")
      };
    }
    await m2mAuthTokenApi.set(token2);
    setToken(token2);
    return { error: void 0 };
  }, []);
  const state = useMemo(() => {
    return {
      login: login2,
      logout,
      token,
      authenticated,
      updateToken
    };
  }, [authenticated, login2, logout, token, updateToken]);
  return /* @__PURE__ */ jsx(AuthenticationContext.Provider, { value: state, children });
};
var useAuth = () => {
  const ctx = useContext(AuthenticationContext);
  if (!ctx) {
    throw new Error("AuthenticationProvider is not found");
  }
  return ctx;
};

export {
  M2mAuthenticationProvider,
  useAuth
};
//# sourceMappingURL=chunk-3YQYBFME.mjs.map