define('custom:handlers/mietverhaeltnis/rent-collection-action', [], function () {
    
    class RentCollectionActionHandler {
        
        constructor(view) {
            this.view = view;
        }
        
        /**
         * Setup-Methode wird automatisch aufgerufen
         */
        initInitiateRentCollection() {
            // Optional: Button-Logik nach Render
        }
        
        /**
         * Action-Handler (wird bei Button-Click aufgerufen)
         */
        actionInitiateRentCollection() {
            console.log('actionInitiateRentCollection called');
            const model = this.view.model;
            
            // Confirmation Dialog
            this.view.confirm(
                this.view.translate('confirmRentCollection', 'messages', 'CVmhMietverhltnis'),
                () => {
                    console.log('Confirmation accepted, initiating rent collection');
                    this.initiateRentCollection(model.id);
                }
            );
        }
        
        /**
         * AJAX Request zum Backend
         */
        initiateRentCollection(mietverhaeltnisId) {
            Espo.Ui.notify(this.view.translate('pleaseWait', 'messages'));
            
            Espo.Ajax.postRequest('CVmhMietverhltnis/action/initiateRentCollection', {
                id: mietverhaeltnisId
            })
            .then(response => {
                Espo.Ui.success(
                    this.view.translate('rentCollectionCreated', 'messages', 'CVmhMietverhltnis')
                );
                
                // Navigation zum erstellten Mietinkasso
                this.view.getRouter().navigate(
                    '#CMietinkasso/view/' + response.id, 
                    {trigger: true}
                );
            })
            .catch(xhr => {
                console.error('Rent collection initiation failed:', xhr);
                
                let errorMessage = this.view.translate('rentCollectionError', 'messages', 'CVmhMietverhltnis');
                
                if (xhr.status === 403) {
                    errorMessage = this.view.translate('Access denied', 'messages');
                } else if (xhr.status === 404) {
                    errorMessage = this.view.translate('Not found', 'messages');
                }
                
                Espo.Ui.error(errorMessage);
            });
        }
    }
    
    return RentCollectionActionHandler;
});
