/*
 This file is part of GNU Taler
 (C) 2021-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/>
 */

/**
 *
 * @author Sebastian Javier Marchano (sebasjm)
 */

import {
  AccessToken,
  ChallengeResponse,
  FacadeCredentials,
  HttpStatusCode,
  OperationFail,
  OperationOk,
  PaytoString,
  TalerError,
  TalerMerchantApi,
  TalerRevenueHttpClient,
  opFixedSuccess,
} from "@gnu-taler/taler-util";
import {
  BrowserFetchHttpLib,
  useChallengeHandler,
  useTranslationContext,
} from "@gnu-taler/web-util/browser";
import { Fragment, VNode, h } from "preact";
import { useState } from "preact/hooks";
import { NotificationCard } from "../../../../components/menu/index.js";
import { useSessionContext } from "../../../../context/session.js";
import { Notification } from "../../../../utils/types.js";
import { CreatePage } from "./CreatePage.js";
import { BasicOrTokenAuth } from "@gnu-taler/taler-util";
import type {
  HttpRequestLibrary,
  HeadersImpl,
} from "@gnu-taler/taler-util/http";
import { SolveMFAChallenges } from "../../../../components/SolveMFA.js";

export type Entity = TalerMerchantApi.AccountAddDetails;
interface Props {
  onBack?: () => void;
  onConfirm: () => void;
}

export default function CreateValidator({ onConfirm, onBack }: Props): VNode {
  const { state, lib } = useSessionContext();
  const [notif, setNotif] = useState<Notification | undefined>(undefined);

  const { i18n } = useTranslationContext();

  const mfa = useChallengeHandler();
  const [doCreate, repeatCreate] = mfa.withMfaHandler(
    ({ challengeIds, onChallengeRequired }) =>
      async function doCreateImpl(request: Entity) {
        try {
          const resp = await lib.instance.addBankAccount(state.token, request, {
            challengeIds,
          });
          if (resp.type === "fail") {
            if (resp.case === HttpStatusCode.Accepted) {
              onChallengeRequired(resp.body);
              return;
            }
            setNotif({
              message: i18n.str`Could not create account`,
              type: "ERROR",
              description: resp.detail?.hint,
            });
            return;
          }
          onConfirm();
        } catch (error) {
          setNotif({
            message: i18n.str`Could not create account`,
            type: "ERROR",
            description: error instanceof Error ? error.message : String(error),
          });
        }
      },
  );

  if (mfa.pendingChallenge) {
    return (
      <SolveMFAChallenges
        currentChallenge={mfa.pendingChallenge}
        onCompleted={repeatCreate}
        onCancel={mfa.doCancelChallenge}
      />
    );
  }

  return (
    <>
      <NotificationCard notification={notif} />
      <CreatePage onBack={onBack} onCreate={doCreate} />
    </>
  );
}

export enum TestRevenueErrorType {
  ANOTHER_ACCOUNT,
  CANT_VALIDATE,
}

export async function testRevenueAPI(
  revenueAPI: URL,
  creds: FacadeCredentials | undefined,
): Promise<
  | OperationOk<PaytoString>
  | OperationFail<TestRevenueErrorType.CANT_VALIDATE>
  | OperationFail<HttpStatusCode.NotFound>
  | OperationFail<HttpStatusCode.Unauthorized>
  | OperationFail<HttpStatusCode.BadRequest>
  | TalerError
> {
  const httpLib: HttpRequestLibrary = new BrowserFetchHttpLib();
  const api = new TalerRevenueHttpClient(revenueAPI.href, httpLib);
  const auth: BasicOrTokenAuth | undefined =
    creds === undefined
      ? undefined
      : creds.type === "none"
        ? undefined
        : creds.type === "basic"
          ? {
              type: "basic",
              username: creds.username,
              password: creds.password,
            }
          : creds.type === "bearer"
            ? {
                type: "bearer",
                token: creds.token as AccessToken,
              }
            : undefined;

  try {
    const config = await api.getConfig(auth);

    if (config.type === "fail") {
      return config;
    }

    const resp = await api.getHistory(auth);
    if (resp.type === "fail") {
      return resp;
    }

    if (!resp.body.credit_account) {
      return {
        type: "fail",
        case: TestRevenueErrorType.CANT_VALIDATE,
        detail: undefined,
      };
    }
    return opFixedSuccess(resp.body.credit_account as PaytoString);
  } catch (err) {
    if (err instanceof TalerError) {
      return err;
      // return {
      //   type: "fail",
      //   case: TestRevenueErrorType.GENERIC_ERROR,
      //   detail: err.errorDetail,
      // };
    }
    throw err;
  }
}
