class OpeningHour < ApplicationRecord
  belongs_to :service_center

  default_scope do
    select(
      %(*,
        "from"::time + (DATE_TRUNC('week', NOW()::date) - '1 days'::interval + week_day * '1 days'::interval) AS from,
        "to"::time + (DATE_TRUNC('week', NOW()::date) - '1 days'::interval + week_day * '1 days'::interval) AS to
      ).squish
    )
  end

  scope :week_days, lambda {
    where(week_day: 0..6).order(Arel.sql("array_position(ARRAY[1, 2, 3, 4, 5, 6, 0]::integer[], week_day)"))
  }

  def self.open_by_settings?
    RecurringOpeningHour.where('NOW() BETWEEN "from" AND "to"')&.first
  end

  def self.next_open
    RecurringOpeningHour.where('"from" > NOW()')&.first
  end

  def self.closes_today_at
    RecurringOpeningHour.where(week_day: Date.current.wday)&.first&.to
  end
end
