// app/modules/catalog/static/vendor/js/product-create.js
/**
 * Vendor product creation page logic
 */

const vendorProductCreateLog = window.LogConfig.loggers.vendorProductCreate ||
    window.LogConfig.createLogger('vendorProductCreate', false);

vendorProductCreateLog.info('Loading...');

function vendorProductCreate() {
    vendorProductCreateLog.info('vendorProductCreate() called');

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

        // Set page identifier
        currentPage: 'products',

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

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

        // Form data
        form: {
            title: '',
            brand: '',
            vendor_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._vendorProductCreateInitialized) return;
            window._vendorProductCreateInitialized = true;

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

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

                vendorProductCreateLog.info('Product create page initialized');
            } catch (err) {
                vendorProductCreateLog.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 (vendor_id from JWT token)
                const response = await apiClient.post('/vendor/products/create', {
                    title: this.form.title,
                    brand: this.form.brand || null,
                    vendor_sku: this.form.vendor_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');
                }

                vendorProductCreateLog.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) {
                vendorProductCreateLog.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;
            }
        }
    };
}

vendorProductCreateLog.info('Loaded successfully');
