class Provider < ApplicationRecord
  has_many :provider_contacts, dependent: :destroy
  has_many :title_provider_groups, dependent: :destroy
  belongs_to :pixtech, optional: true
  belongs_to :provider_type
  has_many :images

  validates :name, :string_key, :copyright_rule, :country, presence: true
  accepts_nested_attributes_for :provider_contacts, allow_destroy: true, reject_if: :provider_contacts_rejectable?

  scope :invisible, -> { where(visible: false) }
  scope :no_pixtech, -> { where(pixtech_id: nil)}
  scope :non_local, -> { where(local: 0) }
  scope :local, -> { where(local: 1) }
  scope :group_string_key, -> { where("pp_string_key = string_key") }
  scope :agency, -> { where(provider_type_id: 1) }
  scope :photographer_agency, -> { where(provider_type_id: 2) }

  mount_uploader :logo, LogoUploader
  mount_uploader :pdf, PdfUploader
  mount_uploader :formu, FormuUploader

  validates_presence_of :pixtech_id, if: -> {provider_type_id == 2}
  validates_presence_of :pp_string_key, if: -> {pixtech_id.present?}

  before_save :update_pp_string_key, if: -> {string_key_changed? || pp_string_key.blank?}

  def visible_text
    @visible_text ||= I18n.t('provider_visibles')[visible]
  end

  def actif_text
    I18n.t("provider_actif.#{actif}")
  end

  def agency_of_photographer_agency
    Provider.group_string_key.find_by("string_key = ?", pp_string_key)
  end

  def provider_contacts_rejectable?(attr)
    attr['first_name'].blank? && attr['last_name'].blank? && attr['email'].blank? && attr['phone'].blank? && attr['portable'].blank?
  end

  private

  def update_pp_string_key
    assign_attributes(pp_string_key: string_key)
  end
end
