/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

define([
    'jquery',
    'ko',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/grid/popups/keyword-analysis-progress',
    'WriteTextAI_WriteTextAI/js/model/grid/reference-products',
    'WriteTextAI_WriteTextAI/js/magento/grid/columns/column',
    'WriteTextAI_WriteTextAI/js/model/total-credits'
], function (
    $,
    ko,
    keywordAnalysis,
    keywordAnalysisProgressModel,
    referenceProducts,
    Column,
    totalCredits
) {
    'use strict';

    return Column.extend({
        defaults: {
            statusRunning: 'Running'
        },

        /** @inheritdoc */
        initialize: function () {
            this._super();
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .track([]);

            this.hasProAccess = ko.computed(function () {
                return totalCredits.hasProAccess();
            }, this);

            return this;
        },

        /**
         * Open single editor.
         *
         * @param {Object} record
         * @returns {void}
         */
        showEditPage: function (record) {
            var action = {
                provider:
                    'wtai_categories_grid_listing.wtai_categories_grid_listing.categories_columns.actions',
                target: 'applyAction',
                params: ['edit', '${ $.$data.rowIndex }']
            };

            this.applySingleAction(record._rowIndex, action);
        },

        /**
         * Get breadcrumbs.
         *
         * @param {Object} record
         *
         * @returns {string}
         */
        getBreadcrumbs: function (record) {
            if (record.breadcrumbs) {
                return record.breadcrumbs;
            }
        },

        /**
         * Check if keyword analysis is in progress.
         *
         * @param {Object} record
         * @returns {Boolean}
         */
        isKeywordAnalysisInProgress: function (record) {
            return ko.computed(function () {
                try {
                    return this.checkIfOptimizing(record);
                } catch (error) {
                    return false;
                }
            }, this);
        },

        /**
         * Check if keyword analysis failed.
         *
         * @param {Object} record
         * @returns {Boolean}
         */
        isKeywordAnalysisFailed: function (record) {
            return ko.computed(function () {
                try {
                    if (!this.hasProAccess()) {
                        return false;
                    }

                    var failedIds = keywordAnalysisProgressModel.status().failedIds || [];
                    var failedInBulk = failedIds.includes(record.entity_id);
                    var failedInSingle = keywordAnalysis.statuses().find(function (status) {
                        return Number(status.storeId) === Number(record.store_id) &&
                            Number(status.recordId) === Number(record.entity_id) &&
                            status.status === 'Failed';
                    });
                    
                    var isOptimizing = this.checkIfOptimizing(record);
                    var keywordAnalysisStatusFailed = record['optimization_status'] === 'Failed' &&
                        isOptimizing === undefined;
                    
                    return failedInBulk || failedInSingle || keywordAnalysisStatusFailed;
                } catch (error) {
                    return false;
                }
            }, this);
        },

        /**
         * Check if keyword analysis is optimizing.
         *
         * @param {Object} record
         * @returns {Boolean}
         */
        checkIfOptimizing: function (record) {
            var isCategoryOptimizing = keywordAnalysis.statuses().find(function (status) {
                return Number(status.storeId) === Number(referenceProducts.storeId()) &&
                    Number(status.recordId) === Number(record.entity_id) &&
                    status.status === 'Running' &&
                    status.recordType === 'Category';
            });
            var isBulkOptimizing = keywordAnalysisProgressModel.status().status === this.statusRunning &&
                keywordAnalysisProgressModel.status().queuedIds.includes(record.entity_id);
            return isBulkOptimizing || isCategoryOptimizing;
        }
    });
});
