# frozen_string_literal: true

class UxToolkitChecklistItemsController < ApplicationController
  before_action :require_login
  before_action :find_visible_issue
  before_action :require_checklist_edit_permission
  before_action :find_checklist_item, only: [:update, :destroy, :toggle]

  def create
    @checklist_item = UxToolkitChecklistItem.new(checklist_item_params)
    @checklist_item.issue = @issue
    @checklist_item.position = UxToolkitChecklistItem.next_position_for(@issue)
    @checklist_item.created_by = User.current
    @checklist_item.updated_by = User.current

    if @checklist_item.save
      flash[:notice] = l(:notice_ux_toolkit_checklist_item_added)
    else
      flash[:error] = checklist_error(@checklist_item, :error_ux_toolkit_checklist_item_add_failed)
    end

    redirect_to issue_path(@issue)
  end

  def update
    @checklist_item.updated_by = User.current

    if @checklist_item.update(checklist_item_params)
      flash[:notice] = l(:notice_ux_toolkit_checklist_item_updated)
    else
      flash[:error] = checklist_error(@checklist_item, :error_ux_toolkit_checklist_item_update_failed)
    end

    redirect_to issue_path(@issue)
  end

  def toggle
    @checklist_item.updated_by = User.current
    if @checklist_item.is_done?
      @checklist_item.reopen
    else
      @checklist_item.mark_done_by(User.current)
    end

    if @checklist_item.save
      message_key = @checklist_item.is_done? ? :notice_ux_toolkit_checklist_item_done : :notice_ux_toolkit_checklist_item_reopened
      flash[:notice] = l(message_key)
    else
      flash[:error] = checklist_error(@checklist_item, :error_ux_toolkit_checklist_item_change_failed)
    end

    redirect_to issue_path(@issue)
  end

  def destroy
    if @checklist_item.destroy
      UxToolkitChecklistItem.normalize_positions_for(@issue)
      flash[:notice] = l(:notice_ux_toolkit_checklist_item_deleted)
    else
      flash[:error] = l(:error_ux_toolkit_checklist_item_delete_failed)
    end

    redirect_to issue_path(@issue)
  end

  private

  def find_visible_issue
    @issue = Issue.visible(User.current).find(params[:issue_id])
    @project = @issue.project
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def require_checklist_edit_permission
    return if RedmineUxToolkit::Services::Checklists.edit_allowed?(@issue, User.current)

    flash[:error] = l(:error_ux_toolkit_checklist_permission_denied)
    redirect_to issue_path(@issue)
  end

  def find_checklist_item
    @checklist_item = UxToolkitChecklistItem.where(issue_id: @issue.id).find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def checklist_item_params
    params.require(:ux_toolkit_checklist_item).permit(:subject)
  end

  def checklist_error(item, fallback_key)
    item.errors.full_messages.to_sentence.presence || l(fallback_key)
  end
end
