# frozen_string_literal: true

# == Schema Information
#
# Table name: auth_providers
#
#  id         :bigint           not null, primary key
#  data       :text(65535)
#  provider   :string(191)
#  uid        :string(191)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  user_id    :bigint
#
# Indexes
#
#  index_auth_providers_on_provider_and_uid  (provider,uid) UNIQUE
#  index_auth_providers_on_user_id           (user_id)
#
class AuthProvider < ApplicationRecord
  belongs_to :user

  serialize :data, JSON

  after_create do
    user.save
    # SaveAvatarJob.perform_later(self.id) unless user.avatar.attached?
  end

  def avatar
    if provider == "github"
      data["info"]["image"]
    elsif provider == "twitter"
      data["info"]["image"]
    elsif provider["google_oauth2"]
      data["info"]["image"]
    end
  end

  def save_img
    downloaded_image = open(avatar, read_timeout: 10)
    user.avatar.attach(
      io: downloaded_image,
      filename: File.basename(URI.parse(avatar).path)
    )
  end
end
