# frozen_string_literal: true

module Gitlab
  module FeatureFlagAlert
    class Milestone
      include Comparable

      def initialize(value)
        @value = value
      end

      def value
        @value || 0.0
      end

      def present?
        !@value.nil?
      end

      def ago(num_milestones)
        major, minor = value.split(".").map(&:to_i)

        older_major = minor >= num_milestones ? major : major - 1
        older_minor = (0..12).to_a[minor - num_milestones]

        self.class.new([older_major, older_minor].join("."))
      end

      def +(other)
        major, minor = value.split(".").map(&:to_i)

        # Releases are "base 12" because they consist of 12 numbers from 0 - 11.
        # We can do the math using a base-10 number and then use a modulo to convert it back to base 12.
        total = (major * 12) + minor + other
        new_major, new_minor = total.divmod(12)

        self.class.new([new_major, new_minor].join("."))
      end

      def <=>(other)
        other = self.class.new(other) unless other.is_a?(self.class)

        Gem::Version.new(value.to_s) <=> Gem::Version.new(other.value.to_s)
      end

      def inspect
        @value || "N/A"
      end
      alias to_s inspect
    end
  end
end
