# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    module IssueAssignToMeAndStart
      module_function

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

      def target_status
        status_id = target_status_id
        status_id.present? ? IssueStatus.find_by(id: status_id.to_i) : nil
      end

      def target_status_id
        settings = Setting.plugin_redmine_ux_toolkit || {}
        status_id = settings['assign_to_me_and_start_status_id'].to_s
        status_id.match?(/\A\d+\z/) ? status_id : ''
      end

      def assigned_and_started?(issue, user = User.current, status = target_status)
        issue &&
          user&.logged? &&
          status &&
          issue.assigned_to_id == user.id &&
          issue.status_id == status.id
      end

      def status_allowed?(issue, user = User.current, status = target_status)
        return false unless issue && user&.logged? && status
        return false unless RedmineUxToolkit::Compatibility.safe_attribute?(issue, 'status_id', user)

        # Redmine applies tracker, project, role, author and assignee workflow rules here.
        RedmineUxToolkit::Compatibility.allowed_issue_statuses(issue, user).map(&:id).include?(status.id)
      end

      def available?(issue, user = User.current)
        return false unless enabled?

        status = target_status
        return false unless status
        return false if assigned_and_started?(issue, user, status)
        return false unless IssueAssignToMe.assignable_to_user?(issue, user)

        status_allowed?(issue, user, status)
      end
    end
  end
end
