# typed: strict
class Domain::PostFile < ReduxApplicationRecord
  include HasAuxTable

  self.table_name = "domain_post_files"

  belongs_to :post,
             foreign_key: :post_id,
             class_name: "::Domain::Post",
             touch: true
  belongs_to :log_entry, class_name: "::HttpLogEntry", optional: true

  has_one :blob,
          class_name: "::BlobFile",
          through: :log_entry,
          source: :response

  has_many :bit_fingerprints,
           class_name: "::Domain::PostFile::BitFingerprint",
           dependent: :destroy,
           inverse_of: :post_file

  has_many :thumbnails,
           class_name: "::Domain::PostFile::Thumbnail",
           dependent: :destroy,
           inverse_of: :post_file

  scope :for_post_type,
        ->(post_klass) do
          post_klass = T.cast(post_klass, T.class_of(Domain::Post))
          joins(:post).where(post: { type: post_klass.name })
        end

  enum :state,
       {
         pending: "pending",
         ok: "ok",
         file_error: "file_error",
         retryable_error: "retryable_error",
         terminal_error: "terminal_error",
         removed: "removed",
       },
       prefix: "state"

  validates :state, presence: true

  after_initialize do
    self.state ||= "pending" if new_record?
    self.type ||= self.class.name if new_record?
  end

  sig { returns(T.nilable(String)) }
  def content_type
    return nil unless log_entry = self.log_entry
    return nil unless response = log_entry.response
    response.content_type ||
      begin
        return nil unless blob = self.blob
        blob.content_type
      end
  end

  sig { returns(T.nilable(String)) }
  def sha256
    blob&.sha256
  end

  sig { returns(Integer) }
  def retry_count
    super || 0
  end
end
