module UserImportable
  extend ActiveSupport::Concern

  included do
    with_options if: :context_import? do |import|
      import.validates :first_name, :last_name, :status, presence: true
      import.validate :presence_of_profile
    end
    attr_accessor :profile
    class_attribute :last_imported_mail_wait
  end

  def send_imported_mail
    token = set_reset_password_token
    self.class.last_imported_mail_wait ||= Time.now
    self.class.last_imported_mail_wait += 5.seconds
    self.class.last_imported_mail_wait = Time.now if self.class.last_imported_mail_wait < Time.now
    UserMailer.with(user: self, token: token).imported.deliver_later(wait_until: self.class.last_imported_mail_wait)
  end

  class_methods do
    def import(row)
      # prepare attributes
      params = row.symbolize_keys
      params[:context] = 'import'
      params[:status] = case params.delete(:active).to_s
                        when '1'
                          :active
                        when '0'
                          :inactive
                        else
                          nil
                        end
      params[:profile] = params.delete(:profil)
      params[:title_attributes] = { title_provider_group_name_id: TitleProviderGroupName.find_by(name: params[:profile])&.id }
      params[:country_id] = IptcCountry.find_by(code: params.delete(:country_code))&.id
      billing_information_attrs = %i[billing_company siret billing_address billing_zip_code billing_city billing_country_id billing_email].reduce({}) do |r, attr|
        r.tap { |b| b[attr] = params.delete(attr) }
      end
      params[:billing_informations_attributes] = [billing_information_attrs]

      # pre-validation
      params[:max_daily_downloads] ||= 0

      # create
      user = new(params)
      if user.save
        user.after_sign_up
        user.send_imported_mail if user.active?
        return 'OK'
      else
        return "#{I18n.t('error')} : #{user.errors.full_messages.join(', ')}"
      end
    rescue Exception => e
      return "#{I18n.t('error')} : #{e.message}"
    end
  end

  private

  def presence_of_profile
    if active?
      if profile.blank?
        errors.add :profile, :blank
      elsif title.title_provider_group_name.blank?
        errors.add :profile, :missing
      end
    end
  end
end
