module Promotions
  class BackfillChannel < Promotions::Base
    attributes :id, :user_id, :login, :priority, :title, :image_url,
               :created_on, :updated_on, :inserted_at, :updated_at,
               :sponsored, :reporter, :description_rendered,
               :description_raw, :language, :active

    validates_format_of :language, with:  /\A[a-z]+(-[a-z]+)?\z/,
                                   allow_blank: true,
                                   unless: :is_editing,
                                   multiline: false,
                                   message: 'Invalid language format. Acceptable languages should be a single language like en or en-gb'

    self.base_path = '/admin/backfill_channels'
    self.entity = 'backfill_channel'
    self.ignored_audit_updates = [:user_id, :language, :id]

    # !(v === false) because if v = false then v.blank? === true, therefore the change is not tracked
    def update_body()
      params = attributes.except(:id, :created_on, :inserted_at, :login, :reporter, :updated_on, :updated_at, :user_id, :language).delete_if{ |k, v| v.blank? && !(v === false) }
      {backfill_channel: params}
    end

    def save_body
      {backfill_channel: attributes.except(:reporter, :description_rendered)}
    end

    # still defined in each service level class because the definition of attributes rewrites the instantiation
    # of the base level attributes
    def active
      self.class.booleanize @active
    end

    def sponsored
      self.class.booleanize @sponsored
    end

    def priority
      @priority.to_i
    end

    # will be removed when the column is removed
    def updated_on
      @updated_on ||= DateTime.parse(@updated_on) rescue nil
    end

    def created_on
      @created_on ||= DateTime.parse(@created_on) rescue nil
    end
  end
end
