/**
 * SimplyIN Payment - Payment Status Poller
 * Handles polling for payment status after 3D Secure redirect
 */
define([
    'jquery',
    'mage/translate',
    'Simplyin_Payment/js/model/ajax-client'
], function ($, $t, ajaxClient) {
    'use strict';

    return {
        /**
         * Polling interval in milliseconds (2 seconds)
         */
        pollInterval: 2000,

        /**
         * Maximum number of polling attempts (30 = 60 seconds total)
         */
        maxAttempts: 30,

        /**
         * Current polling attempt counter
         */
        currentAttempt: 0,

        /**
         * Timer ID for polling interval
         */
        timerId: null,

        /**
         * Callback functions for status changes
         */
        callbacks: {
            onCompleted: null,
            onFailed: null,
            onTimeout: null,
            onPending: null
        },

        /**
         * Start polling for payment status
         * @param {string} paymentId - Payment ID to check
         * @param {string} authToken - Authentication token
         * @param {Object} callbacks - Callback functions for status changes
         * @returns {Promise} - Resolves when polling completes
         */
        startPolling: function (paymentId, authToken, callbacks) {
            var self = this;

            // Reset state
            this.currentAttempt = 0;
            this.stopPolling();

            // Set callbacks
            if (callbacks) {
                this.callbacks = $.extend(this.callbacks, callbacks);
            }

            return new Promise(function (resolve, reject) {
                self.poll(paymentId, authToken, resolve, reject);
            });
        },

        /**
         * Internal polling function
         * @param {string} paymentId - Payment ID to check
         * @param {string} authToken - Authentication token
         * @param {Function} resolve - Promise resolve function
         * @param {Function} reject - Promise reject function
         */
        poll: function (paymentId, authToken, resolve, reject) {
            var self = this;

            // Check if max attempts reached
            if (this.currentAttempt >= this.maxAttempts) {
                this.stopPolling();
                
                var timeoutError = {
                    code: 'TIMEOUT',
                    message: $t('Payment verification timed out. Please check your order status or contact support.')
                };

                if (this.callbacks.onTimeout) {
                    this.callbacks.onTimeout(timeoutError);
                }
                
                reject(timeoutError);
                return;
            }

            this.currentAttempt++;

            // Make status check request
            this.checkStatus(paymentId, authToken).then(function (response) {
                if (!response.success) {
                    // API error - continue polling
                    self.scheduleNextPoll(paymentId, authToken, resolve, reject);
                    return;
                }

                var status = response.status;

                switch (status) {
                    case 'COMPLETED':
                    case 'PAID':
                    case 'SUCCESS':
                        self.stopPolling();
                        
                        if (self.callbacks.onCompleted) {
                            self.callbacks.onCompleted(response);
                        }
                        
                        resolve(response);
                        break;

                    case 'FAILED':
                    case 'REJECTED':
                    case 'DECLINED':
                        self.stopPolling();
                        
                        var failedError = {
                            code: 'PAYMENT_FAILED',
                            message: response.errorMessage || $t('Payment was declined'),
                            data: response
                        };

                        if (self.callbacks.onFailed) {
                            self.callbacks.onFailed(failedError);
                        }
                        
                        reject(failedError);
                        break;

                    case 'PENDING':
                    case 'PROCESSING':
                    default:
                        // Still pending - continue polling
                        if (self.callbacks.onPending) {
                            self.callbacks.onPending(response, self.currentAttempt, self.maxAttempts);
                        }
                        
                        self.scheduleNextPoll(paymentId, authToken, resolve, reject);
                        break;
                }
            }).catch(function (error) {
                console.error('Payment status check error:', error);
                // Network error - continue polling
                self.scheduleNextPoll(paymentId, authToken, resolve, reject);
            });
        },

        /**
         * Schedule next polling attempt
         * @param {string} paymentId - Payment ID to check
         * @param {string} authToken - Authentication token
         * @param {Function} resolve - Promise resolve function
         * @param {Function} reject - Promise reject function
         */
        scheduleNextPoll: function (paymentId, authToken, resolve, reject) {
            var self = this;

            this.timerId = setTimeout(function () {
                self.poll(paymentId, authToken, resolve, reject);
            }, this.pollInterval);
        },

        /**
         * Check payment status via API
         * @param {string} paymentId - Payment ID to check
         * @param {string} authToken - Authentication token
         * @returns {Promise} - Resolves with status response
         */
        checkStatus: function (paymentId, authToken) {
            return new Promise(function (resolve, reject) {
                ajaxClient.postSilent('simplyin/api/checkPaymentStatus', {
                    paymentId: paymentId,
                    authToken: authToken
                }).done(function (response) {
                    resolve(response);
                }).fail(function (xhr, status, error) {
                    reject({
                        code: 'NETWORK_ERROR',
                        message: error || $t('Network error while checking payment status'),
                        xhr: xhr
                    });
                });
            });
        },

        /**
         * Stop polling and clear timer
         */
        stopPolling: function () {
            if (this.timerId) {
                clearTimeout(this.timerId);
                this.timerId = null;
            }
        },

        /**
         * Reset poller state
         */
        reset: function () {
            this.stopPolling();
            this.currentAttempt = 0;
            this.callbacks = {
                onCompleted: null,
                onFailed: null,
                onTimeout: null,
                onPending: null
            };
        },

        /**
         * Get current polling progress
         * @returns {Object} - Progress information
         */
        getProgress: function () {
            return {
                currentAttempt: this.currentAttempt,
                maxAttempts: this.maxAttempts,
                isPolling: this.timerId !== null,
                elapsedSeconds: this.currentAttempt * (this.pollInterval / 1000),
                remainingSeconds: (this.maxAttempts - this.currentAttempt) * (this.pollInterval / 1000)
            };
        }
    };
});
