# == Schema Information
#
# Table name: todos
#
#  id                :integer          not null, primary key
#  user_id           :integer
#  due_at            :datetime
#  completed_at      :datetime
#  name              :string           default(""), not null
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#  recurring_todo_id :integer
#  due_date          :date
#
# Indexes
#
#  index_todos_on_recurring_todo_id  (recurring_todo_id)
#  index_todos_on_user_id            (user_id)
#
# Foreign Keys
#
#  fk_rails_...  (recurring_todo_id => recurring_todos.id)
#  fk_rails_...  (user_id => users.id)
#

class Todo < ApplicationRecord
  belongs_to :user
  belongs_to :recurring_todo, optional: true
  validates :name, presence: true
  validate :due_date_due_at_validation

  scope :on_day, -> (date) {
    where(due_date: date).or(
      where('due_at >= ?', date.beginning_of_day)
      .where('due_at <= ?', date.end_of_day)
    )
  }

  scope :past_due, -> {
    where('due_at < ?', Time.current).or(
      where('due_date < ?', Date.current)
    )
  }

  scope :recurring, -> { where.not(recurring_todo_id: nil) }
  scope :incomplete, -> { where(completed_at: nil) }
  scope :completed, -> { where.not(completed_at: nil) }

  private

    def due_date_due_at_validation
      if due_date && due_at
        self.errors.add(:base, 'cannot set due_date and due_at')
      end
      if due_date.nil? && due_at.nil?
        self.errors.add(:base, 'must set due_date or due_at')
      end
    end
end
