import { h, r as registerInstance, c as createEvent } from './index-CV0Pyo1O.js';
import { J as JustifiAnalytics } from './Analytics-C76Y5Pqf.js';
import { C as ComponentErrorSeverity, b as ComponentErrorCodes } from './Plaid-DxSkT8pY.js';
import { m as makeGetBusiness, b as makePostProvisioning } from './payment-provisioning-actions-ByGe6983.js';
import { B as BusinessService } from './business.service-BpvtCKI5.js';
import { A as Api } from './Api-BulOmiMS.js';
import './Pagination-CLHwhyvu.js';
import { C as CountryCode, B as Business, c as checkProvisioningStatus } from './Business-BcNb9bVO.js';
import { c as checkPkgVersion } from './check-pkg-version-D5BxTNyL.js';
import { l as isTokenExpired } from './utils-C25uIOK0.js';
import { t as text } from './parts-CPKMvyV_.js';
import { S as StyledHost } from './styled-host-D84RBv1W.js';
import { H as Header1 } from './header-1-evYxFIGN.js';
import './event-types-CZfYo5-1.js';
import { B as BusinessFormClickActions } from './event-types-XYgDHrVL.js';
import { P as PaymentProvisioningLoading } from './payment-provisioning-loading-Dve2xQA4.js';
import './package-CqcLgdsl.js';
import './utils-CVYvs2hZ.js';
import './config-state-kKn89dp1.js';
import './index-cDVGjRkU.js';
import './dinero-HXpYMWUU.js';
import './skeleton-BEHo2ypu.js';

const 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 (h("div", { class: "row gap-3 p-5" }, h("div", { class: "col-12" }, h(Header1, { text: "Business Already Provisioned" })), h("div", { class: "col-12", part: text }, h("p", null, "We have already received the onboarding information for this business."))));
};

const PaymentProvisioningSubmissionComplete = () => {
    return (h("div", { class: "row gap-3 p5" }, h("div", { class: "col-12" }, h(Header1, { text: "You're all set for now" })), h("div", { class: "col-12", part: text }, 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 (h("div", { class: "row gap-3 p-5" }, h("div", { class: "col-12" }, h(Header1, { text: "Something went wrong" })), h("div", { class: "col-12", part: text }, 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) {
        registerInstance(this, hostRef);
        this.clickEvent = createEvent(this, "click-event", 7);
        this.errorEvent = createEvent(this, "error-event", 7);
        this.submitEvent = 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 = 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(response.data);
                        this.businessProvisioned = 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: ComponentErrorCodes.PROVISIONING_REQUESTED,
                                severity: 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: 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();
        this.analytics = new 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: ComponentErrorCodes.MISSING_PROPS,
                severity: ComponentErrorSeverity.ERROR,
            });
            return;
        }
        if (isTokenExpired(this.authToken)) {
            this.errorEvent.emit({
                message: 'auth-token is expired',
                errorCode: ComponentErrorCodes.NOT_AUTHENTICATED,
                severity: ComponentErrorSeverity.ERROR,
            });
            return;
        }
        this.getBusiness = makeGetBusiness({
            authToken: this.authToken,
            businessId: this.businessId,
            service: new BusinessService(),
        });
        this.postProvisioning = 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 (h(StyledHost, null, h(PaymentProvisioningLoading, null)));
        }
        if (this.businessProvisioned) {
            return (h(StyledHost, null, h(PaymentProvisioningAlreadyProvisioned, null)));
        }
        if (this.formSubmitted) {
            return (h(StyledHost, null, h(PaymentProvisioningSubmissionComplete, null)));
        }
        if (this.submissionFailed) {
            return (h(StyledHost, null, h(PaymentProvisioningSubmissionFailed, null)));
        }
        return (h(StyledHost, null, h("div", { class: "row gap-3" }, h(Header1, { text: this.formTitle }), 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 }), h("div", { class: "d-flex justify-content-between align-items-center" }, h("div", { class: "d-flex align-items-center", part: text }, this.stepCounter), 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"]
    }; }
};

export { JustifiPaymentProvisioning as justifi_payment_provisioning };
