// static/admin/js/module-config.js
// Module configuration management for platform modules

const moduleConfigLog = window.LogConfig?.loggers?.moduleConfig || window.LogConfig?.createLogger?.('moduleConfig') || console;

function adminModuleConfig(platformCode, moduleCode) {
    return {
        // Inherit base layout functionality from init-alpine.js
        ...data(),

        // Page-specific state
        currentPage: 'platforms',
        platformCode: platformCode,
        moduleCode: moduleCode,
        loading: true,
        error: null,
        successMessage: null,
        saving: false,

        // Reset confirm state
        showResetConfirm: false,

        // Data
        platformId: null,
        platformName: '',
        moduleInfo: null,
        config: {},

        async init() {
            // Guard against duplicate initialization
            if (window._moduleConfigInitialized) {
                moduleConfigLog.warn('Already initialized, skipping');
                return;
            }
            window._moduleConfigInitialized = true;

            moduleConfigLog.info('=== MODULE CONFIG PAGE INITIALIZING ===');
            moduleConfigLog.info('Platform code:', this.platformCode);
            moduleConfigLog.info('Module code:', this.moduleCode);

            try {
                await this.loadPlatform();
                await this.loadModuleConfig();
                moduleConfigLog.info('=== MODULE CONFIG PAGE INITIALIZED ===');
            } catch (error) {
                moduleConfigLog.error('Failed to initialize module config page:', error);
                this.error = 'Failed to load page data. Please refresh.';
            }
        },

        async refresh() {
            this.error = null;
            this.successMessage = null;
            await this.loadModuleConfig();
        },

        async loadPlatform() {
            try {
                const platform = await apiClient.get(`/admin/platforms/${this.platformCode}`);
                this.platformId = platform.id;
                this.platformName = platform.name;
                moduleConfigLog.info('Loaded platform:', platform.name);
            } catch (error) {
                moduleConfigLog.error('Failed to load platform:', error);
                throw error;
            }
        },

        async loadModuleConfig() {
            this.loading = true;
            this.error = null;

            try {
                if (!this.platformId) {
                    throw new Error('Platform not loaded');
                }

                this.moduleInfo = await apiClient.get(
                    `/admin/module-config/platforms/${this.platformId}/modules/${this.moduleCode}/config`
                );

                // Initialize config with current values
                this.config = { ...this.moduleInfo.config };

                moduleConfigLog.info('Loaded module config:', {
                    moduleCode: this.moduleCode,
                    config: this.config
                });
            } catch (error) {
                moduleConfigLog.error('Failed to load module config:', error);
                this.error = error.message || 'Failed to load module configuration';
            } finally {
                this.loading = false;
            }
        },

        async saveConfig() {
            this.saving = true;
            this.error = null;
            this.successMessage = null;

            try {
                const response = await apiClient.put(
                    `/admin/module-config/platforms/${this.platformId}/modules/${this.moduleCode}/config`,
                    { config: this.config }
                );

                // Update local state with response
                this.moduleInfo = response;
                this.config = { ...response.config };

                this.successMessage = 'Configuration saved successfully';
                moduleConfigLog.info('Saved module config:', this.config);
            } catch (error) {
                moduleConfigLog.error('Failed to save module config:', error);
                this.error = error.message || 'Failed to save configuration';
            } finally {
                this.saving = false;
            }
        },

        async resetToDefaults() {
            this.saving = true;
            this.error = null;
            this.successMessage = null;

            try {
                const response = await apiClient.post(
                    `/admin/module-config/platforms/${this.platformId}/modules/${this.moduleCode}/reset`
                );

                // Update local state with defaults
                this.config = { ...response.config };

                // Reload full config to get schema_info
                await this.loadModuleConfig();

                this.successMessage = 'Configuration reset to defaults';
                moduleConfigLog.info('Reset module config to defaults');
            } catch (error) {
                moduleConfigLog.error('Failed to reset module config:', error);
                this.error = error.message || 'Failed to reset configuration';
            } finally {
                this.saving = false;
            }
        }
    };
}
