class GoogleOauthToken < ApplicationRecord
  audited

  belongs_to :user, inverse_of: :google_oauth_token

  after_initialize :refresh_access_token, unless: :new_record?

  before_destroy :remove_token

  def generate_oauth_token(auth_code)
    resp = Google::OauthTokenService.new.get_access_token(auth_code)

    self.access_token = resp['access_token']
    self.refresh_token = resp['refresh_token']
    self.scope = resp['scope']
    self.expires_at = Time.zone.at(resp['expires_in'] + Time.zone.now.to_time.to_i)
  end

  def refresh_access_token
    return if expires_at > Time.zone.now

    data = Google::OauthTokenService.new.request_token_from_google(refresh_token)
    return if data['access_token'].blank?

    update(
      access_token: data['access_token'],
      expires_at: Time.zone.now + data['expires_in'].to_i.seconds
    )
  end

  def token
    JSON.parse(Google::OauthTokenService.new.get_token(access_token))
  end

  def valid_token?(authorize_scopes=nil)
    flag = Google::OauthTokenService.new.validate_access_token?(access_token)
    return flag if authorize_scopes.blank?

    scopes = scope.split(' ')
    authorize_scopes.split(' ').each { |s| return false unless scopes.include?(s) }
    flag
  end

  def remove_token
    Google::OauthTokenService.new.remove_token(access_token)
  end
end
