# frozen_string_literal: true

class UxToolkitCronMonitorState < ActiveRecord::Base
  DEFAULT_NAME = 'default'
  CHECK_INTERVAL = 10.minutes
  LOCK_TIMEOUT = 2.minutes

  validates :name, presence: true, uniqueness: true

  def self.default_record
    find_or_create_by!(name: DEFAULT_NAME)
  rescue ActiveRecord::RecordNotUnique
    find_by!(name: DEFAULT_NAME)
  end

  def self.claim_check!(now: Time.current)
    state = default_record
    updated_rows = where(id: state.id)
                   .where('locked_until IS NULL OR locked_until <= ?', now)
                   .where('last_checked_at IS NULL OR last_checked_at <= ?', now - CHECK_INTERVAL)
                   .update_all(
                     last_checked_at: now,
                     locked_until: now + LOCK_TIMEOUT,
                     updated_at: now
                   )

    updated_rows == 1 ? state.reload : nil
  end
end
