// static/admin/js/store-create.js
/**
 * Admin Store Create Page
 * Handles store creation form with merchant selection
 */

// Use centralized logger
const storeCreateLog = window.LogConfig.loggers.stores;

storeCreateLog.info('Loading store create module...');

function adminStoreCreate() {
    storeCreateLog.debug('adminStoreCreate() called');

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

        // Page identifier
        currentPage: 'stores',

        // Merchants list for dropdown
        merchants: [],
        loadingMerchants: true,

        // Platforms list for selection
        platforms: [],

        // Form data matching StoreCreate schema
        formData: {
            merchant_id: '',
            store_code: '',
            subdomain: '',
            name: '',
            description: '',
            letzshop_csv_url_fr: '',
            letzshop_csv_url_en: '',
            letzshop_csv_url_de: '',
            platform_ids: []
        },

        // UI state
        loading: false,
        successMessage: false,
        errorMessage: '',
        createdStore: null,

        // Initialize
        async init() {
            // Guard against multiple initialization
            if (window._adminStoreCreateInitialized) return;
            window._adminStoreCreateInitialized = true;

            try {
                storeCreateLog.info('Initializing store create page');
                await Promise.all([
                    this.loadMerchants(),
                    this.loadPlatforms()
                ]);
            } catch (error) {
                storeCreateLog.error('Failed to initialize store create:', error);
            }
        },

        // Load merchants for dropdown
        async loadMerchants() {
            this.loadingMerchants = true;
            try {
                const response = await apiClient.get('/admin/merchants?limit=1000');
                this.merchants = response.merchants || [];
                storeCreateLog.debug('Loaded merchants:', this.merchants.length);
            } catch (error) {
                storeCreateLog.error('Failed to load merchants:', error);
                this.errorMessage = 'Failed to load merchants. Please refresh the page.';
            } finally {
                this.loadingMerchants = false;
            }
        },

        // Load platforms for selection
        async loadPlatforms() {
            try {
                const response = await apiClient.get('/admin/platforms');
                this.platforms = response.platforms || response.items || [];
                storeCreateLog.debug('Loaded platforms:', this.platforms.length);
            } catch (error) {
                storeCreateLog.error('Failed to load platforms:', error);
                this.platforms = [];
            }
        },

        // Auto-generate subdomain from store name
        autoGenerateSubdomain() {
            if (!this.formData.name) {
                return;
            }

            // Convert name to subdomain format
            const subdomain = this.formData.name
                .toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '') // Remove special chars
                .replace(/\s+/g, '-')          // Replace spaces with hyphens
                .replace(/-+/g, '-')           // Replace multiple hyphens with single
                .replace(/^-|-$/g, '');        // Remove leading/trailing hyphens

            this.formData.subdomain = subdomain;
            storeCreateLog.debug('Auto-generated subdomain:', subdomain);
        },

        // Create store
        async createStore() {
            this.loading = true;
            this.errorMessage = '';
            this.successMessage = false;
            this.createdStore = null;

            try {
                storeCreateLog.info('Creating store:', {
                    merchant_id: this.formData.merchant_id,
                    store_code: this.formData.store_code,
                    name: this.formData.name
                });

                // Prepare payload - only include non-empty values
                const payload = {
                    merchant_id: parseInt(this.formData.merchant_id),
                    store_code: this.formData.store_code.toUpperCase(),
                    subdomain: this.formData.subdomain.toLowerCase(),
                    name: this.formData.name
                };

                // Add optional fields if provided
                if (this.formData.description) {
                    payload.description = this.formData.description;
                }
                if (this.formData.letzshop_csv_url_fr) {
                    payload.letzshop_csv_url_fr = this.formData.letzshop_csv_url_fr;
                }
                if (this.formData.letzshop_csv_url_en) {
                    payload.letzshop_csv_url_en = this.formData.letzshop_csv_url_en;
                }
                if (this.formData.letzshop_csv_url_de) {
                    payload.letzshop_csv_url_de = this.formData.letzshop_csv_url_de;
                }

                // Add platform assignments
                if (this.formData.platform_ids && this.formData.platform_ids.length > 0) {
                    payload.platform_ids = this.formData.platform_ids.map(id => parseInt(id));
                }

                const response = await apiClient.post('/admin/stores', payload);

                storeCreateLog.info('Store created successfully:', response.store_code);

                // Store created store details
                this.createdStore = {
                    store_code: response.store_code,
                    name: response.name,
                    subdomain: response.subdomain,
                    merchant_name: response.merchant_name
                };

                this.successMessage = true;

                // Reset form
                this.formData = {
                    merchant_id: '',
                    store_code: '',
                    subdomain: '',
                    name: '',
                    description: '',
                    letzshop_csv_url_fr: '',
                    letzshop_csv_url_en: '',
                    letzshop_csv_url_de: '',
                    platform_ids: []
                };

                // Scroll to top to show success message
                window.scrollTo({ top: 0, behavior: 'smooth' });

                // Redirect after 3 seconds
                setTimeout(() => {
                    window.location.href = `/admin/stores/${response.store_code}`;
                }, 3000);

            } catch (error) {
                storeCreateLog.error('Failed to create store:', error);

                // Parse error message
                if (error.message) {
                    this.errorMessage = error.message;
                } else if (error.detail) {
                    this.errorMessage = error.detail;
                } else {
                    this.errorMessage = 'Failed to create store. Please try again.';
                }

                window.scrollTo({ top: 0, behavior: 'smooth' });
            } finally {
                this.loading = false;
            }
        }
    };
}

storeCreateLog.info('Store create module loaded');
