class Plan < ApplicationRecord
  SLUGS = %w[free premium_light premium_full].freeze
  EXTERNAL_PLATFORMS = %w[youtube facebook twitch].freeze
  PREMIUM_SLUGS = %w[premium_light premium_full].freeze

  has_many :subscriptions, dependent: :restrict_with_error

  validates :slug, presence: true, uniqueness: true, inclusion: { in: SLUGS }
  validates :name, presence: true

  scope :ordered, -> {
    order(Arel.sql("CASE slug WHEN 'free' THEN 0 WHEN 'premium_light' THEN 1 ELSE 2 END"))
  }

  def self.[](slug)
    find_by!(slug: slug.to_s)
  end

  def self.tier(slug)
    SLUGS.index(slug.to_s) || 0
  end

  def tier
    self.class.tier(slug)
  end

  def allows_platform?(platform)
    return false if platform.to_s == "youtube" && !youtube_enabled?

    Array(features["platforms"]).map(&:to_s).include?(platform.to_s)
  end

  def feature(key)
    features[key.to_s]
  end

  def recordings_enabled?
    feature("recordings_enabled") == true
  end

  def recording_days
    feature("recording_days").to_i
  end

  def max_staff_transmission
    val = feature("max_staff_transmission")
    return legacy_max_staff if val.nil? && feature("max_staff").present?

    val.nil? ? nil : val.to_i
  end

  def max_staff_regia
    val = feature("max_staff_regia")
    return legacy_max_staff if val.nil? && feature("max_staff").present?

    val.nil? ? nil : val.to_i
  end

  def max_staff
    t = max_staff_transmission
    r = max_staff_regia
    return legacy_max_staff if legacy_max_staff.positive? && t.nil? && r.nil? && feature("max_staff").present?
    return nil if t.nil? && r.nil?

    (t || 0) + (r || 0)
  end

  def youtube_mode
    feature("youtube_mode")&.to_s
  end

  def concurrent_streams_limit
    val = feature("concurrent_streams_limit")
    val.nil? ? nil : val.to_i
  end

  def phone_download_enabled?
    feature("phone_download_enabled") == true
  end

  def youtube_enabled?
    feature("youtube_enabled") == true
  end

  def premium?
    slug.in?(PREMIUM_SLUGS)
  end

  private

  def legacy_max_staff
    feature("max_staff").to_i
  end
end
