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

/**
 * Result of a generic operation that can fail.
 */
export type Result<T, Err> = ResultOk<T> | ResultError<Err, unknown>;

export interface ResultOk<T> {
  readonly tag: "ok";
  readonly value: T;
}

export interface ResultError<Err, Detail = unknown> {
  readonly tag: "error";
  readonly error: Err;
  readonly detail: Detail;
}

export const Result = {
  of<T>(value: T): ResultOk<T> {
    return { tag: "ok", value };
  },
  error<Err>(error: Err): ResultError<Err, undefined> {
    return { tag: "error", error, detail: undefined };
  },
  errorWithDetail<Err, Detail = void>(
    error: Err,
    detail: Detail,
  ): ResultError<Err, Detail> {
    return { tag: "error", error, detail };
  },
  unpack<T, Err>(r: Result<T, Err>): T {
    if (r.tag !== "ok") {
      throw Error("expected success result");
    }
    return r.value;
  },
  isOk<T, Err>(r: Result<T, Err>): r is ResultOk<T> {
    return r.tag === "ok";
  },
  isError<T, Err>(r: Result<T, Err>): r is ResultError<Err> {
    return r.tag === "error";
  },
  orUndefined<T>(r: Result<T, any>): T | undefined {
    if (r.tag !== "ok") {
      return undefined;
    }
    return r.value;
  },
  orElse<T, TA>(r: Result<T, any>, alt: TA): T | TA {
    if (r.tag !== "ok") {
      return alt;
    }
    return r.value;
  },
};
