# frozen_string_literal: true

class UxToolkitProjectSettingsController < ApplicationController
  before_action :find_project_by_project_id
  before_action :require_ux_toolkit_project_module
  before_action :authorize_project_settings

  def update
    project_setting = UxToolkitProjectSetting.find_or_initialize_by(project: @project)
    project_setting.assign_attributes(project_setting_params)

    if project_setting.save
      flash[:notice] = l(:notice_ux_toolkit_project_settings_saved)
    else
      flash[:error] = project_setting.errors.full_messages.to_sentence
    end

    redirect_to settings_project_path(@project, tab: 'redmine_ux_toolkit')
  end

  private

  def require_ux_toolkit_project_module
    return true if ux_toolkit_project_module_enabled?

    render_403
    false
  end

  def authorize_project_settings
    render_403 unless User.current.allowed_to?(:edit_project, @project)
  end

  def ux_toolkit_project_module_enabled?
    if @project.respond_to?(:module_enabled?)
      @project.module_enabled?(:redmine_ux_toolkit)
    else
      @project.enabled_modules.where(name: 'redmine_ux_toolkit').exists?
    end
  end

  def project_setting_params
    params.fetch(:ux_toolkit_project_setting, {}).permit(:new_issue_notice_text)
  end
end
