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

define([
    'jquery',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/grid/slug-notice'
], function (
    $,
    Component,
    _,
    slugNotice
) {
    'use strict';

    /**
     * @var {Component} self
     */
    var self;

    return Component.extend({
        defaults: {
            selector: '#wtai-cannibalization-analyzer-container'
        },

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

            self = this;

            this.initializeSlugAnalyzer();
        },

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

            return this;
        },

        /**
         * Initialize the slug analyzer
         *
         * @returns {void}
         */
        initializeSlugAnalyzer: function () {
            $.ajax({
                url: self.analyzeUrl,
                type: 'post',
                dataType: 'json',
                data: {
                    slugs: self.slugs,
                    storeId: self.storeId
                }
            }).done(function (response) {
                console.log(response);
                slugNotice.cmsUrls(response.cmsUrls);

                if (response.hasProducts) {
                    self.redirect(response, 'product');
                } else if (response.hasCategories) {
                    self.redirect(response, 'category');
                } else {
                    self.redirect(response, 'product');
                }
            });
        },

        /**
         * Remove the cannibalization analyzer
         *
         * @returns {void}
         */
        removeCannibalizationAnalyzer: function () {
            $(self.selector).fadeOut(400, function () {
                $(this).remove();
            });
            $('.wtai-grid-index').removeClass('wtai-cannibalizing');
        },

        /**
         * Redirect to the categories URL
         *
         * @param {Object} response
         * @param {string} entityType
         * @returns {void}
         */
        redirect: function (response, entityType) {
            var currentParams = new URLSearchParams(window.location.search);
            var url = entityType === 'category' ? self.categoriesUrl : self.productsUrl;
            var recordIds = entityType === 'category' ? response.categoryIds[response.storeId] : response.productIds[response.storeId];

            /* Remove wtai_slugs from URL parameters */
            currentParams.delete('wtai_slugs');

            /* Add cmsUrls as a URL parameter (encoded) */
            currentParams.append('wtai_cms_urls', encodeURIComponent(JSON.stringify(response.cmsUrls)));
            
            /* Add recordIds as a URL parameter (encoded) */
            if (recordIds && recordIds.length > 0) {
                currentParams.append('wtai-record-ids', recordIds.join(','));
            }

            /* Add storeId as a URL parameter */
            currentParams.append('wtai-store-id', response.storeId);

            /* Add storeUrls as a URL parameter */
            currentParams.append('wtai_store_urls', encodeURIComponent(JSON.stringify(response.storeUrls)));

            /* Add categoryIds as a URL parameter (encoded) */
            if (response.hasCategories) {
                currentParams.append('wtai_category_ids', encodeURIComponent(JSON.stringify(response.categoryIds)));
            }

            /* Add productIds as a URL parameter (encoded) */
            if (response.hasProducts) {
                currentParams.append('wtai_product_ids', encodeURIComponent(JSON.stringify(response.productIds)));
            }

            if (!response.hasCategories && !response.hasProducts) {
                currentParams.append('wtai-record-ids', null);
            }

            /* Add the current params to the url */
            if (currentParams.toString()) {
                url += (url.indexOf('?') > -1 ? '&' : '?') + currentParams.toString();
            }

            /* Redirect to the url */
            window.location.href = url;
        }
    });
});
