# app/models/research_document.rb
class ResearchDocument < ApplicationRecord
  belongs_to :respondent_category

  has_attached_file :document
  do_not_validate_attachment_file_type :document

  validates_attachment_presence :document
  validate :document_must_not_be_media

  VIEWABLE_EXTENSIONS = {
    pdf: %w[pdf],
    text: %w[txt json xml]
  }.freeze

  # Lucide icon names (not CSS classes) — rendered via lucide_icon in views
  ICON_MAP = {
    "pdf" => "file-text",
    "doc" => "file-type",        "docx" => "file-type",
    "xls" => "file-spreadsheet", "xlsx" => "file-spreadsheet", "csv" => "file-spreadsheet",
    "ppt" => "presentation",     "pptx" => "presentation",
    "zip" => "file-archive",     "rar"  => "file-archive", "7z" => "file-archive",
    "txt" => "file-text",        "md"   => "file-text", "log" => "file-text",
    "rtf" => "file-text",
    "odt" => "file-type", "ods" => "file-spreadsheet", "odp" => "presentation"
  }.freeze

  def extension
    File.extname(document_file_name.to_s).delete(".").downcase
  end

  def viewable_type
    VIEWABLE_EXTENSIONS.find { |_type, exts| exts.include?(extension) }&.first
  end

  def viewable?
    viewable_type.present?
  end

  def icon_name
    ICON_MAP.fetch(extension, "file")
  end

  def human_size
    ActiveSupport::NumberHelper.number_to_human_size(document_file_size)
  end

  private

  def document_must_not_be_media
    file = document.queued_for_write[:original]
    return if file.blank?

    sniffed_type = Marcel::MimeType.for(file, name: document_file_name, declared_type: document_content_type)
    file.rewind

    if sniffed_type.match?(%r{\A(image|video|audio)/})
      errors.add(:document, "must not be an image, video, or audio file")
      return
    end

    self.document_content_type = sniffed_type
  end
end
