# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    class LandingPageResolver
      DISABLED_VALUES = [false, 0, '0', 'false', 'FALSE'].freeze

      def self.user_override_allowed?
        settings = Setting.plugin_redmine_ux_toolkit || {}
        !DISABLED_VALUES.include?(settings['allow_user_landing_page_override'])
      rescue StandardError => e
        Rails.logger.warn "Redmine UX Toolkit user override setting ignored: #{e.class}: #{e.message}"
        true
      end

      def initialize(user)
        @user = user
      end

      def path
        return nil unless user&.logged?

        (user_override_allowed? ? user_landing_path : nil) || global_landing_path
      rescue StandardError => e
        Rails.logger.warn "Redmine UX Toolkit landing page preference ignored: #{e.class}: #{e.message}"
        nil
      end

      def user_landing_path
        preference = UxToolkitUserPreference.find_by(user_id: user.id)
        return nil unless preference

        preference.resolved_landing_path
      rescue StandardError => e
        Rails.logger.warn "Redmine UX Toolkit user landing page preference ignored: #{e.class}: #{e.message}"
        nil
      end

      def global_landing_path
        settings = Setting.plugin_redmine_ux_toolkit || {}
        landing_page_type = settings['global_landing_page_type'].to_s
        landing_page_value = settings['global_landing_page_value'].to_s

        case landing_page_type
        when UxToolkitUserPreference::LANDING_PAGE_TYPE_MY_PAGE
          '/my/page'
        when UxToolkitUserPreference::LANDING_PAGE_TYPE_MY_WORK
          '/my/work'
        when UxToolkitUserPreference::LANDING_PAGE_TYPE_CUSTOM_URL
          valid_internal_path?(landing_page_value) ? landing_page_value.strip : nil
        else
          nil
        end
      rescue StandardError => e
        Rails.logger.warn "Redmine UX Toolkit global landing page preference ignored: #{e.class}: #{e.message}"
        nil
      end

      def valid_internal_path?(value)
        UxToolkitUserPreference.valid_internal_path?(value)
      end

      def user_override_allowed?
        self.class.user_override_allowed?
      end

      private

      attr_reader :user
    end
  end
end
