# frozen_string_literal: true

class UxToolkitIssueReminderState < ActiveRecord::Base
  DEFAULT_NAME = 'default'
  LOCK_TIMEOUT = 30.minutes
  MESSAGE_LIMIT = 1000

  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!(lock_timeout: LOCK_TIMEOUT)
    state = default_record
    now = Time.current

    updated_rows = where(id: state.id)
                   .where('locked_until IS NULL OR locked_until <= ?', now)
                   .update_all(
                     last_attempt_at: now,
                     last_status: 'running',
                     last_message: I18n.t(:text_ux_toolkit_issue_reminder_run_started),
                     locked_until: now + lock_timeout,
                     updated_at: now
                   )

    updated_rows == 1 ? state.reload : nil
  end

  def release_success!(message)
    now = Time.current
    update!(
      last_successful_at: now,
      last_status: 'success',
      last_message: truncate_message(message),
      locked_until: nil
    )
  end

  def release_failure!(message)
    update!(
      last_status: 'failed',
      last_message: truncate_message(message),
      locked_until: nil
    )
  end

  private

  def truncate_message(message)
    message.to_s.truncate(MESSAGE_LIMIT)
  end
end
