# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    module Checklists
      module_function

      def enabled?
        settings = Setting.plugin_redmine_ux_toolkit || {}
        settings.fetch('enable_checklists', '1').to_s != '0'
      end

      def prevent_closing_with_open_items_enabled?
        return false unless enabled?

        settings = Setting.plugin_redmine_ux_toolkit || {}
        settings.fetch('prevent_closing_with_open_checklist_items', '0').to_s == '1'
      end

      def open_item_count_for(issue)
        return 0 unless issue&.persisted?
        return 0 unless checklist_items_table_exists?

        UxToolkitChecklistItem.where(issue_id: issue.id, is_done: false).count
      rescue ActiveRecord::StatementInvalid => e
        Rails.logger.warn("[redmine_ux_toolkit] Could not count open checklist items: #{e.class.name}")
        0
      end

      def closing_blocked_hint?(issue)
        prevent_closing_with_open_items_enabled? &&
          issue.present? &&
          !RedmineUxToolkit::Compatibility.issue_closed?(issue.status) &&
          open_item_count_for(issue).positive?
      end

      def view_allowed?(issue, user)
        enabled? &&
          issue.present? &&
          user.present? &&
          issue.visible?(user) &&
          user.allowed_to?(:view_ux_toolkit_checklists, issue.project)
      end

      def edit_allowed?(issue, user)
        view_allowed?(issue, user) &&
          user.logged? &&
          user.allowed_to?(:edit_ux_toolkit_checklists, issue.project)
      end

      def template_management_allowed?(user)
        enabled? && user.present? && user.logged? && user.admin?
      end

      def checklist_items_table_exists?
        UxToolkitChecklistItem.table_exists?
      rescue ActiveRecord::ActiveRecordError
        false
      end
    end
  end
end
