# frozen_string_literal: true

class UxToolkitAttachmentTrashRecord < ActiveRecord::Base
  STATUS_TRASHED = 'trashed'
  STATUS_RESTORED = 'restored'
  STATUS_DELETED = 'deleted'
  STATUS_MISSING = 'missing'
  STATUSES = [STATUS_TRASHED, STATUS_RESTORED, STATUS_DELETED, STATUS_MISSING].freeze
  MESSAGE_LIMIT = 1000

  belongs_to :attachment, optional: true
  belongs_to :moved_to_trash_by, class_name: 'User', optional: true
  belongs_to :restored_by, class_name: 'User', optional: true
  belongs_to :permanently_deleted_by, class_name: 'User', optional: true

  validates :attachment_id, presence: true
  validates :original_disk_filename, :original_path, :trash_path, :original_filename, presence: true
  validates :status, inclusion: {in: STATUSES}

  scope :trashed, -> { where(status: STATUS_TRASHED) }
  scope :expired, -> { where('expires_at IS NOT NULL AND expires_at <= ?', Time.current) }

  def self.table_available?
    ActiveRecord::Base.connection.data_source_exists?('ux_toolkit_attachment_trash_records')
  rescue ActiveRecord::ActiveRecordError
    false
  end

  def self.active_for_attachment_ids(ids)
    return {} if ids.blank? || !table_available?

    trashed.where(attachment_id: ids).order(id: :desc).index_by(&:attachment_id)
  end

  def self.latest_for_attachment_ids(ids)
    return {} if ids.blank? || !table_available?

    where(attachment_id: ids).order(id: :desc).to_a.index_by(&:attachment_id)
  end

  def mark_missing!(message)
    update!(
      status: STATUS_MISSING,
      last_message: truncate_message(message)
    )
  end

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