class Image < ApplicationRecord
  belongs_to :user
  has_many :image_tags, dependent: :destroy
  has_many :tags, through: :image_tags

  has_one_attached :file

  validates :title, presence: true
  validates :file, presence: true, on: :create

  # Status for review process
  enum :status, { pending: 0, approved: 1, rejected: 2 }, default: :pending

  # Scopes for filtering
  scope :pending, -> { where(status: :pending) }
  scope :approved, -> { where(status: :approved) }
  scope :rejected, -> { where(status: :rejected) }

  def self.ransackable_attributes(auth_object = nil)
    [ "created_at", "id", "id_value", "status", "title", "updated_at", "user_id" ]
  end

  def self.ransackable_associations(auth_object = nil)
    [ "image_tags", "tags", "user" ]
  end

  # Returns the URL for the attached file
  def file_url
    file.attached? ? Rails.application.routes.url_helpers.rails_blob_path(file, only_path: true) : nil
  end

  # Method to add tags to an image
  def add_tags(tag_names)
    tag_names.each do |name|
      tag = Tag.find_or_create_by(name: name.downcase.strip)
      tags << tag unless tags.include?(tag)
    end
  end
end