# frozen_string_literal: true

class Feed < ApplicationRecord
  include ActiveModel::ForbiddenAttributesProtection

  belongs_to :source
  has_many :fetches, class_name: 'FeedFetch'
  has_many :messages, as: :messageable

  scope :fetch_needed, lambda {
    where('next_fetch_at < ?', Time.zone.now).order(:next_fetch_at)
  }

  scope :archived, lambda {
    joins(source: :canteen).where(sources: {canteens: {state: 'archived'}})
  }

  scope :inactive, lambda {
    where('(schedule IS NULL OR id IN (?))', Feed.archived.select(:id))
  }

  scope :active, lambda {
    where('(schedule IS NOT NULL AND id NOT IN (?))', Feed.archived.select(:id))
  }

  delegate :canteen, to: :source

  def feed_timespans
    {
      lastday: fetches.where('executed_at > ?', 1.day.ago),
      lastweek: fetches.where('executed_at > ?', 1.week.ago),
      total: fetches
    }
  end
end

# frozen_string_literal: true

class Feed < ApplicationRecord
  include ActiveModel::ForbiddenAttributesProtection

  belongs_to :source
  has_many :fetches, class_name: 'FeedFetch'
  has_many :messages, as: :messageable

  scope :fetch_needed, lambda {
    where('next_fetch_at < ?', Time.zone.now).order(:next_fetch_at)
  }

  scope :archived, lambda {
    joins(source: :canteen).where(sources: {canteens: {state: 'archived'}})
  }

  scope :inactive, lambda {
    where('(schedule IS NULL OR id IN (?))', Feed.unscoped.archived.select(:id))
  }

  scope :active, lambda {
    where('(schedule IS NOT NULL AND id NOT IN (?))', Feed.unscoped.archived.select(:id))
  }

  delegate :canteen, to: :source

  def feed_timespans
    {
      lastday: fetches.where('executed_at > ?', 1.day.ago),
      lastweek: fetches.where('executed_at > ?', 1.week.ago),
      total: fetches
    }
  end
end

Fix Rails 6.1 deprecation on class method scopes
Fix Rails 6.1 deprecation on class method scopes

Fix the following deprecation warning:

    Class level methods will no longer inherit scoping from `inactive` in
    Rails 6.1. To continue using the scoped relation, pass it into the block
    directly. To instead access the full set of models, as Rails 6.1 will,
    use `Feed.unscoped`, or `Feed.default_scoped` if a model has default
    scopes.

The archived scope here does not need to inherit any existing scopes or
conditions from Feed. It is therefore changed into
`Feed.unscoped.archived`.
