// The public contract of botprot.js: the `window.OpenTicket` global and its types.
//
// All members of `OpenTicket` are optional: each OpenTicket script progressively enhances
// the shared global with its own members, so none of them are guaranteed to be present.
//
// The types live in the global `OpenTicket` namespace, e.g. `OpenTicket.BotProtOptions`, so scripts without
// imports and the types of skins can use them, wherever this file is placed. They are exported here as well.

export type BotProtOptions = OpenTicket.BotProtOptions;
export type BotProtFailureCode = OpenTicket.BotProtFailureCode;
export type BotProtFailure = OpenTicket.BotProtFailure;

declare global {
    // noinspection ES6ConvertVarToLetConst
    var OpenTicket: OpenTicket | undefined;

    interface OpenTicket {
        // Resolves to the final token; rejects with a BotProtFailure, or the reason of the signal option when
        // cancelled. Only one BotProt runs per page: creating another cancels the previous one (an AbortError).
        createBotProt?: (identifier: string, options?: OpenTicket.BotProtOptions) => Promise<string>;

        // Clears the persisted state of `identifier`, such as a final token after an order, so the next createBotProt
        // starts over. Pass the same retrieveToken and storeToken as to createBotProt.
        clearBotProt?: (identifier: string, options?: OpenTicket.BotProtOptions) => void;

        // Enables debug logging to the console, e.g. `OpenTicket.debug = true`.
        // Strings 'true', '1', 'yes' and 'on' are accepted as well. Read on every log, so it can be
        // toggled at any time.
        debug?: boolean | string;
    }

    // Types only, never values: `OpenTicket` itself is the variable above.
    namespace OpenTicket {
        interface BotProtOptions {
            // Called once, when the first step should be rendered. It must return the element the BotProt client can
            // render the step in, and that element must be in the document. The client renders each step into it,
            // replacing its content, and never removes it.
            // Without this option, the client appends a default element to the document, and removes it before final
            // or fail is called, or when cancelled.
            // Default: `undefined`.
            show?(this: void): HTMLElement;

            // Called when BotProt sends the user to an external service, such as a waiting room, which returns them to
            // returnUrl. It must navigate to `url`. BotProt waits while the page goes away; when this option throws,
            // BotProt fails ('config').
            // Default: `window.location.assign(url)`.
            redirect?(this: void, url: string): void;

            // The URL a redirect returns the user to, absolute or relative to the document. BotProt adds a token
            // to it: after returning, calling createBotProt again with the same identifier continues where it left
            // off. Missing, `null` or empty means the default; anything that is not a valid URL fails BotProt
            // ('config') right away.
            // Default: `window.location.href` when createBotProt is called.
            returnUrl?: string | null;

            // Persist the state of BotProt, so a refresh or a return from a redirect continues where it left off. Give
            // both or neither; with only one of them, localStorage is used.
            // retrieveToken must return the value last stored under `key`, or `null` when there is none.
            // storeToken must store `value` under `key` as-is, where an empty value means forgetting the key.
            // `expiresAt` (the JWT's expiry) is for storage that expires values itself, such as a cookie; it is not
            // given when forgetting. An expired value is forgotten on retrieval anyway.
            // Keys are per identifier, and values are opaque. A token BotProt added to the return URL takes priority
            // over what is stored, unless it was used before, which BotProt checks through the storage.
            // Note: this includes final tokens, which may have been used already. On a shared device, such as a POS
            // device, or after a successful order, they may have to be cleaned up; BotProt only forgets them when it
            // starts again after they have expired or a successful order clears it.
            // Default: localStorage, under `BotProt:Token:Last:{identifier}` and `BotProt:Token:Queries:{identifier}`.
            retrieveToken?(this: void, key: string): string | null;

            // See retrieveToken.
            storeToken?(this: void, key: string, value: string, expiresAt?: Date): void;

            // Called once with the final token. BotProt is done with the element it rendered in. The default element is
            // removed right before this is called; the element returned by show is left as it is.
            // Default: `undefined`.
            final?(this: void, token: string): void;

            // Called once when BotProt fails critically, with:
            // - message: safe to show to visitors as-is; showing it, with a way to retry, is a complete implementation.
            // - code: allows handling failures separately (see BotProtFailureCode); optional.
            // - error: the details for developers, e.g. to log or report (see BotProtFailure).
            // BotProt is done with the element it rendered in. The default element is removed right before this is
            // called; the element returned by show is left as it is.
            // Default: `undefined`.
            fail?(this: void, message: string, code: BotProtFailureCode, error: BotProtFailure): void;

            // Cancels BotProt, e.g. when the user navigates away in a single page application. Cancelling is not a
            // failure: fail is not called, and createBotProt rejects with the reason of the signal. The default element
            // is removed, and the element returned by show is left as it is. Scripts of a step that already started
            // cannot be stopped.
            // Default: `undefined`.
            signal?: AbortSignal;
        }

        // Why BotProt failed:
        // - 'config': this page or deployment is set up incorrectly (e.g. no usable return URL).
        // - 'network': BotProt could not be reached.
        // - 'status': BotProt responded with an error status.
        // - 'response': BotProt responded with something unusable.
        // - 'rejected': BotProt concluded the user is a bot; retrying is unlikely to help.
        // - 'limit': the user exceeded the number of attempts.
        // - 'unexpected': anything else.
        type BotProtFailureCode = 'config' | 'network' | 'status' | 'response' | 'rejected' | 'limit' | 'unexpected';

        // The error BotProt fails with: passed to the fail option, and the reason createBotProt rejects with.
        // Its `message` is meant for developers (logs, error reporting); `visitorMessage` is safe to show to visitors.
        interface BotProtFailure extends Error {
            readonly code: BotProtFailureCode;
            readonly visitorMessage: string;
        }
    }

    interface DocumentEventMap {
        'BotProt:Client:Ready': CustomEvent<OpenTicket>;
    }
}
