# Ruby Calculator - Interactive calculator built with Ruby on Rails
# Author: RSK World (Molla Samser, Founder | Rima Khatun, Designer & Tester)
# Contact: help@rskworld.in | +91 93305 39277
# Website: https://rskworld.in
# Year: 2026
# Description: Build a fully functional calculator using Ruby on Rails with modern UI

class FavoriteCalculation < ApplicationRecord
  belongs_to :calculation_history, optional: true
  
  validates :name, presence: true, length: { minimum: 2, maximum: 100 }
  validates :expression, presence: true
  validates :result, presence: true
  validates :category, presence: true, inclusion: { in: %w[custom formula conversion constant] }
  
  scope :by_category, ->(category) { where(category: category) }
  scope :recent, -> { order(created_at: :desc) }
  scope :alphabetical, -> { order(:name) }
  
  CATEGORIES = {
    'custom' => 'Custom Calculation',
    'formula' => 'Mathematical Formula',
    'conversion' => 'Unit Conversion',
    'constant' => 'Mathematical Constant'
  }
  
  def self.get_by_category(category)
    by_category(category)
  end
  
  def self.popular
    joins(:calculation_history)
      .group('favorite_calculations.id')
      .order('COUNT(calculation_histories.id) DESC')
      .limit(10)
  end
  
  def self.search(query)
    where("name ILIKE ? OR expression ILIKE ?", "%#{query}%", "%#{query}%")
  end
  
  def category_name
    CATEGORIES[category]
  end
  
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
