# frozen_string_literal: true

class UxToolkitTrackerChecklistTemplatesController < ApplicationController
  layout 'admin'

  before_action :require_login
  before_action :require_admin_management

  def index
    load_defaults
  end

  def update
    save_defaults
    flash[:notice] = l(:notice_ux_toolkit_tracker_checklist_defaults_saved)
    redirect_to ux_toolkit_tracker_checklist_templates_path
  rescue ActiveRecord::RecordInvalid
    load_defaults
    flash.now[:error] = l(:error_ux_toolkit_tracker_checklist_defaults_save_failed)
    render :index, status: :unprocessable_entity
  end

  private

  def require_admin_management
    if !RedmineUxToolkit::Services::Checklists.enabled?
      flash[:error] = l(:error_ux_toolkit_tracker_checklist_defaults_disabled)
      redirect_to plugin_settings_path(:redmine_ux_toolkit)
      return false
    end

    return true if User.current.admin?

    render_403
    false
  end

  def load_defaults
    @trackers = Tracker.sorted.to_a
    @templates = UxToolkitChecklistTemplate.active.with_items.ordered.to_a
    @defaults = UxToolkitTrackerChecklistTemplate.where(tracker_id: @trackers.map(&:id)).index_by(&:tracker_id)
  end

  def save_defaults
    submitted_defaults = tracker_default_params
    allowed_template_ids = UxToolkitChecklistTemplate.active.with_items.pluck(:id).map(&:to_s)

    UxToolkitTrackerChecklistTemplate.transaction do
      Tracker.find(submitted_defaults.keys).each do |tracker|
        template_id = submitted_defaults[tracker.id.to_s].to_s
        mapping = UxToolkitTrackerChecklistTemplate.find_or_initialize_by(tracker_id: tracker.id)

        if template_id.blank?
          mapping.destroy! if mapping.persisted?
        elsif allowed_template_ids.include?(template_id)
          mapping.update!(checklist_template_id: template_id)
        else
          mapping.errors.add(:checklist_template_id, :invalid)
          raise ActiveRecord::RecordInvalid, mapping
        end
      end
    end
  end

  def tracker_default_params
    params.fetch(:tracker_checklist_templates, {}).permit!.to_h
  end
end
