class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :tracks, dependent: :destroy
  has_many :groups, dependent: :destroy

  has_one_attached :logo

  before_validation :downcase_username

  validates :logo,
    content_type: {
      in: [:jpg, :jpeg, :png, :gif],
      message: 'must be an image'
    },
    size: {
      less_than: ActiveStorage::MAX_UPLOAD_FILESIZE_MB.megabytes,
      message: "must be smaller than #{ActiveStorage::MAX_UPLOAD_FILESIZE_MB}MB"
    }

  validates :username,
    presence: true,
    uniqueness: true,
    exclusion: {
      in: %w(health sidekiq subscription users rails),
      message: "%{value} is already in use"
    }

  validate :website_is_url

  # Virtual attribute used to sign-in. This is either username or email.
  # See User.find_for_database_authentication() for how this works.
  attr_accessor :login

  def self.find_for_database_authentication(warden_conditions)
    conditions = warden_conditions.dup
    login = conditions.delete(:login)

    where(conditions).where([
      "lower(username) = :value OR lower(email) = :value",
      { value: login.strip.downcase }
    ]).first
  end

  def to_param
    username
  end

  def admin?
    username == 'huntca'
  end

  def subscribed?
    stripe_subscription_id.present?
  end

  def customer?
    stripe_customer_id.present?
  end

  def send_devise_notification(notification, *args)
    devise_mailer.send(notification, self, *args).deliver_later
  end

  private

  def downcase_username
    self.username = self.username.downcase
  end

  def website_is_url
    return if website.blank?

    invalid = begin
      !!!URI.parse(website).host
    rescue URI::InvalidURIError
      # Not valid
    end

    errors.add(:website, 'is not a valid url') if invalid
  end
end
