/*
 This file is part of GNU Taler
 (C) 2022-2024 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
import {
  AccessToken,
  HttpStatusCode,
  KycProcessClientInformationWithEtag,
  opFixedSuccess,
} from "@gnu-taler/taler-util";
import {
  useAsync,
  useExchangeApiContext,
  useLongPolling,
} from "@gnu-taler/web-util/browser";
import _useSWR, { SWRHook, mutate } from "swr";
const useSWR = _useSWR as unknown as SWRHook;

export function revalidateKycInfo() {
  return mutate(
    (key) => Array.isArray(key) && key[key.length - 1] === "checkKycInfo",
    undefined,
    { revalidate: true },
  );
}

export function useKycInfo(token?: AccessToken) {
  const {
    lib: { exchange: api },
  } = useExchangeApiContext();

  const prev = useAsync(
    token === undefined
      ? undefined
      : () => {
          return api.checkKycInfoSpa(token, undefined);
        },
    [token],
  );

  const result = useLongPolling(
    prev,
    (result) => {
      if (!result || result.type === "fail") return undefined;
      if (!result.body.requirements.length) return undefined;
      return result.body;
    },
    async (latestStatus: KycProcessClientInformationWithEtag) => {
      const res = await api.checkKycInfoSpa(token!, latestStatus.etag, {
        timeoutMs: 5000,
      });
      if (res.type === "fail" && res.case === HttpStatusCode.NotModified) {
        return opFixedSuccess(latestStatus);
      }
      return res;
    },
    [token],
  );

  return result;
}
