class ServiceCenter < ApplicationRecord
  has_many :opening_hours, dependent: :destroy

  after_update_commit :defer_requests

  def self.open?
    first.open
  end

  def self.closed?
    !first.open
  end

  def self.open!
    first.update(open: true)
  end

  def self.close!
    first.update(open: false)
  end

  def self.schedule_open_job
    next_open_time = OpeningHour.next_open["from"]
    return if next_open_time < Time.current
    return if open_job_queued?

    OpenServiceCenterJob.set(wait_until: next_open_time).perform_later
  end

  def self.open_job_queued?
    Sidekiq::ScheduledSet.new.any? do |job|
      job.args.any? { |j| j["job_class"] == "OpenServiceCenterJob" }
    end
  end

  def self.opening_hours_label
    if ServiceCenter.open?
      I18n.t("nav.client.service_center_closes_at", time: OpeningHour.closes_today_at&.strftime("%H:%M"))
    elsif OpeningHour.open_by_settings?
      I18n.t("nav.client.service_center_closed_temporarily")
    else
      next_open = OpeningHour.next_open

      day_name = if next_open["week_day"] == Date.current.wday
                   I18n.t("shared.today")
                 else
                   I18n.l(next_open["from"], format: "%A")
                 end

      I18n.t("nav.client.service_center_opens_at", day_name:, time: next_open["from"]&.strftime("%H:%M"))
    end
  end

  def defer_requests
    ServiceRequest.waiting.update_all(status: :deferred) if open_previously_changed? && !self.open
  end
end
