// app/modules/catalog/static/store/js/product-create.js
/**
 * Store product creation page logic
 */

const storeProductCreateLog = window.LogConfig.loggers.storeProductCreate ||
    window.LogConfig.createLogger('storeProductCreate', false);

storeProductCreateLog.info('Loading...');

function storeProductCreate() {
    storeProductCreateLog.info('storeProductCreate() called');

    return {
        // Inherit base layout state
        ...data(),

        // Set page identifier
        currentPage: 'products',

        // Back URL
        get backUrl() {
            return `/store/${this.storeCode}/products`;
        },

        // Loading states
        loading: false,
        saving: false,
        error: '',

        // Form data
        form: {
            title: '',
            brand: '',
            store_sku: '',
            gtin: '',
            price: '',
            currency: 'EUR',
            availability: 'in_stock',
            is_active: true,
            is_featured: false,
            is_digital: false,
            description: ''
        },

        async init() {
            // Load i18n translations
            await I18n.loadModule('catalog');

            // Guard against duplicate initialization
            if (window._storeProductCreateInitialized) return;
            window._storeProductCreateInitialized = true;

            storeProductCreateLog.info('Initializing product create page...');

            try {
                // IMPORTANT: Call parent init first to set storeCode from URL
                const parentInit = data().init;
                if (parentInit) {
                    await parentInit.call(this);
                }

                storeProductCreateLog.info('Product create page initialized');
            } catch (err) {
                storeProductCreateLog.error('Failed to initialize:', err);
                this.error = err.message || 'Failed to initialize';
            }
        },

        async createProduct() {
            if (!this.form.title || !this.form.price) {
                Utils.showToast(I18n.t('catalog.messages.title_and_price_required'), 'error');
                return;
            }

            this.saving = true;
            this.error = '';

            try {
                // Create product directly (store_id from JWT token)
                const response = await apiClient.post('/store/products/create', {
                    title: this.form.title,
                    brand: this.form.brand || null,
                    store_sku: this.form.store_sku || null,
                    gtin: this.form.gtin || null,
                    price: parseFloat(this.form.price),
                    currency: this.form.currency,
                    availability: this.form.availability,
                    is_active: this.form.is_active,
                    is_featured: this.form.is_featured,
                    description: this.form.description || null
                });

                if (!response.ok) {
                    throw new Error(response.message || 'Failed to create product');
                }

                storeProductCreateLog.info('Product created:', response.data);
                Utils.showToast(I18n.t('catalog.messages.product_created_successfully'), 'success');

                // Navigate back to products list
                setTimeout(() => {
                    window.location.href = this.backUrl;
                }, 1000);

            } catch (err) {
                storeProductCreateLog.error('Failed to create product:', err);
                this.error = err.message || I18n.t('catalog.messages.failed_to_create_product');
                Utils.showToast(this.error, 'error');
            } finally {
                this.saving = false;
            }
        }
    };
}

storeProductCreateLog.info('Loaded successfully');
