# frozen_string_literal: true

module RedmineUxToolkit
  module Patches
    module MyControllerPatch
      # The account page has a view hook for fields, but saving separate plugin
      # preference records requires extending the account update transaction.
      def account
        @user = User.current
        @pref = @user.pref
        @ux_toolkit_user_preference = redmine_ux_toolkit_user_preference(@user)
        @ux_toolkit_user_override_allowed = redmine_ux_toolkit_user_override_allowed?

        if request.put?
          @user.safe_attributes = params[:user]
          @user.pref.safe_attributes = params[:pref]
          if @ux_toolkit_user_override_allowed
            @ux_toolkit_user_preference.assign_attributes(redmine_ux_toolkit_preference_params)
          end

          if @user.valid? && redmine_ux_toolkit_preference_valid?
            @user.save
            @user.pref.save
            @ux_toolkit_user_preference.save if @ux_toolkit_user_override_allowed

            respond_to do |format|
              format.html do
                flash[:notice] = l(:notice_account_updated)
                redirect_to my_account_path
              end
              format.api { render_api_ok }
            end
            return
          end

          redmine_ux_toolkit_copy_errors(@ux_toolkit_user_preference, @user)

          respond_to do |format|
            format.html { render action: :account }
            format.api { render_validation_errors(@user) }
          end
        end
      end

      private

      def redmine_ux_toolkit_user_preference(user)
        UxToolkitUserPreference.find_or_initialize_by(user_id: user.id)
      end

      def redmine_ux_toolkit_user_override_allowed?
        RedmineUxToolkit::Services::LandingPageResolver.user_override_allowed?
      end

      def redmine_ux_toolkit_preference_valid?
        return true unless @ux_toolkit_user_override_allowed

        @ux_toolkit_user_preference.valid?
      end

      def redmine_ux_toolkit_preference_params
        source = params[:ux_toolkit_user_preference]
        return {} unless source

        source.permit(:landing_page_type, :landing_page_value)
      end

      def redmine_ux_toolkit_copy_errors(source, target)
        source.errors.full_messages.each do |message|
          target.errors.add(:base, message)
        end
      end
    end
  end
end
