class Site < ApplicationRecord
  self.table_name_prefix = "st_"
  include MetaAttribute

  BUY_LINK = "https://item.taobao.com/item.htm?spm=a230r.1.14.31.6e621411kMkTXS&id=688518819522&ns=1&abbucket=7#detail".freeze

  section "basic" do
    meta_attribute "site_name", type: :string
    meta_attribute "site_email", type: :string
  end

  section "seo" do
    meta_attribute "keywords", type: :string
    meta_attribute "description", type: :string, form_ctrl: "textarea"
  end

  def self.current
    Rails.cache.fetch("site_current") do
      where(selected: true).first # Site.where
    end
  end

  def self.get_ip_country(ip)
    Rails.cache.fetch("ip_country_#{ip}") do
      results = Geocoder.search(ip)
      results&.first&.country
    end
  end

  after_commit :dicard_cache

  private

  def dicard_cache
    Rails.cache.delete("site_current")
  end
end
