'use strict';

var index = require('./index-p7cvUYAE.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var Plaid = require('./Plaid-CPESyiiV.js');
var paymentProvisioningActions = require('./payment-provisioning-actions-P8cbgnKy.js');
var business_service = require('./business.service-BIHpEqmf.js');
var Api = require('./Api-D9vOcUw4.js');
require('./Pagination-Dediz133.js');
var Business = require('./Business-oBifyXkW.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var utils = require('./utils-CYONRFR6.js');
var parts = require('./parts-BXshb_S-.js');
var styledHost = require('./styled-host-Ch0-dxF-.js');
var header1 = require('./header-1-CsBQoo1f.js');
require('./event-types-YOY5TKUN.js');
var eventTypes = require('./event-types-DNOUef41.js');
var paymentProvisioningLoading = require('./payment-provisioning-loading-tM9WWmxv.js');
require('./package-YyJzVqrh.js');
require('./utils-BsnepLy6.js');
require('./config-state-BIgGhhe9.js');
require('./index-W-zoNiyM.js');
require('./dinero-BwNN_k7x.js');
require('./skeleton-DvRCiQlA.js');

const api = Api.Api();
class ProvisionService {
    async postProvisioning(authToken, businessId, product) {
        const endpoint = `entities/provisioning`;
        const body = {
            business_id: businessId,
            product_category: product,
        };
        return api.post({ endpoint, body, authToken });
    }
}

const PaymentProvisioningAlreadyProvisioned = () => {
    return (index.h("div", { class: "row gap-3 p-5" }, index.h("div", { class: "col-12" }, index.h(header1.Header1, { text: "Business Already Provisioned" })), index.h("div", { class: "col-12", part: parts.text }, index.h("p", null, "We have already received the onboarding information for this business."))));
};

const PaymentProvisioningSubmissionComplete = () => {
    return (index.h("div", { class: "row gap-3 p5" }, index.h("div", { class: "col-12" }, index.h(header1.Header1, { text: "You're all set for now" })), index.h("div", { class: "col-12", part: parts.text }, index.h("p", null, "We're reviewing your information and working on your approval. We'll be in touch to let you know once you've been approved (or if we find anything that needs fixing). Have a good one!"))));
};

const PaymentProvisioningSubmissionFailed = () => {
    return (index.h("div", { class: "row gap-3 p-5" }, index.h("div", { class: "col-12" }, index.h(header1.Header1, { text: "Something went wrong" })), index.h("div", { class: "col-12", part: parts.text }, index.h("p", null, "There was an error submitting the provisioning. Your progress has been saved \u2014 please try again later or contact the support team."))));
};

const JustifiPaymentProvisioning = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.submitEvent = index.createEvent(this, "submit-event", 7);
        this.loading = false;
        this.businessLoading = true;
        this.businessProvisioned = false;
        this.formSubmitted = false;
        this.submissionFailed = false;
        this.currentStep = 0;
        this.country = Business.CountryCode.USA;
        this.allowOptionalFields = false;
        this.formTitle = 'Business Information';
        this.refs = [];
        this.setBusinessProvisioned = () => {
            return new Promise((resolve) => {
                this.getBusiness({
                    onSuccess: (response) => {
                        const business = new Business.Business(response.data);
                        this.businessProvisioned = Business.checkProvisioningStatus(business);
                        this.country = business.country_of_establishment;
                        if (this.businessProvisioned) {
                            this.errorEvent.emit({
                                message: 'A request to provision payments for this business has already been submitted.',
                                errorCode: Plaid.ComponentErrorCodes.PROVISIONING_REQUESTED,
                                severity: Plaid.ComponentErrorSeverity.INFO,
                            });
                        }
                        this.businessLoading = false;
                        resolve();
                    },
                    onError: ({ error, code, severity }) => {
                        this.errorEvent.emit({
                            message: error,
                            errorCode: code,
                            severity: severity,
                        });
                        this.businessLoading = false;
                        resolve();
                    },
                });
            });
        };
        this.postProvisioningData = () => {
            this.postProvisioning({
                onSuccess: (response) => {
                    this.formSubmitted = true;
                    this.submitEvent.emit({ response: response });
                },
                onError: ({ error, code, severity }) => {
                    this.submissionFailed = true;
                    this.submitEvent.emit({ response: { error } });
                    this.errorEvent.emit({
                        message: error,
                        errorCode: code,
                        severity: severity,
                    });
                },
            });
        };
        this.incrementSteps = () => {
            if (this.currentStep < this.totalSteps) {
                return this.currentStep++;
            }
        };
        this.decrementSteps = () => {
            if (this.currentStep > 0) {
                this.currentStep -= 1;
            }
        };
        this.previousStepButtonOnClick = () => {
            this.clickEvent.emit({ name: eventTypes.BusinessFormClickActions.previousStep });
            this.decrementSteps();
        };
        this.nextStepButtonOnClick = (e, clickEventName) => {
            e.preventDefault();
            this.clickEvent.emit({ name: clickEventName });
            const currentStep = this.refs[this.currentStep];
            currentStep.validateAndSubmit({ onSuccess: this.incrementSteps });
        };
    }
    propChanged() {
        this.initializeApi();
    }
    handleFormCompleted() {
        this.postProvisioningData();
    }
    handleFormLoading(event) {
        this.loading = event.detail;
    }
    async componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.initializeApi();
        if (this.getBusiness) {
            await this.setBusinessProvisioned();
        }
        else {
            this.businessLoading = false;
        }
        this.refs = new Array(8);
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    initializeApi() {
        if (!this.authToken || !this.businessId) {
            this.errorEvent.emit({
                message: 'auth-token and business-id are required',
                errorCode: Plaid.ComponentErrorCodes.MISSING_PROPS,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
            return;
        }
        if (utils.isTokenExpired(this.authToken)) {
            this.errorEvent.emit({
                message: 'auth-token is expired',
                errorCode: Plaid.ComponentErrorCodes.NOT_AUTHENTICATED,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
            return;
        }
        this.getBusiness = paymentProvisioningActions.makeGetBusiness({
            authToken: this.authToken,
            businessId: this.businessId,
            service: new business_service.BusinessService(),
        });
        this.postProvisioning = paymentProvisioningActions.makePostProvisioning({
            authToken: this.authToken,
            businessId: this.businessId,
            product: 'payment',
            service: new ProvisionService(),
        });
    }
    get formDisabled() {
        return this.loading || this.businessProvisioned;
    }
    get totalSteps() {
        return this.refs.length - 1;
    }
    get stepCounter() {
        return `Step ${this.currentStep + 1} of ${this.totalSteps + 1}`;
    }
    render() {
        if (this.businessLoading) {
            return (index.h(styledHost.StyledHost, null, index.h(paymentProvisioningLoading.PaymentProvisioningLoading, null)));
        }
        if (this.businessProvisioned) {
            return (index.h(styledHost.StyledHost, null, index.h(PaymentProvisioningAlreadyProvisioned, null)));
        }
        if (this.formSubmitted) {
            return (index.h(styledHost.StyledHost, null, index.h(PaymentProvisioningSubmissionComplete, null)));
        }
        if (this.submissionFailed) {
            return (index.h(styledHost.StyledHost, null, index.h(PaymentProvisioningSubmissionFailed, null)));
        }
        return (index.h(styledHost.StyledHost, null, index.h("div", { class: "row gap-3" }, index.h(header1.Header1, { text: this.formTitle }), index.h("payment-provisioning-form-steps", { businessId: this.businessId, authToken: this.authToken, refs: this.refs, currentStep: this.currentStep, allowOptionalFields: this.allowOptionalFields, country: this.country, handleFormLoading: this.handleFormLoading }), index.h("div", { class: "d-flex justify-content-between align-items-center" }, index.h("div", { class: "d-flex align-items-center", part: parts.text }, this.stepCounter), index.h("payment-provisioning-form-buttons", { currentStep: this.currentStep, totalSteps: this.totalSteps, formLoading: this.loading, formDisabled: this.formDisabled, previousStepButtonOnClick: this.previousStepButtonOnClick, nextStepButtonOnClick: this.nextStepButtonOnClick })))));
    }
    static get watchers() { return {
        "authToken": ["propChanged"],
        "businessId": ["propChanged"]
    }; }
};

exports.justifi_payment_provisioning = JustifiPaymentProvisioning;
