module Twitch
  class Reservation < Twitch::Base
    self.primary_attribute = :id
    attributes :login,
               :type,
               :reason,
               :expires_on,
               :existing_user_id

    validates :login, presence: true

    def self.from_attributes(params)
      super(params.slice(*self.attribute_names))
    end

    def self.find(login)
      response = get "/reservations?login=#{login}"

      raise response.body["message"] unless response.success?

      reservation_attributes = response.body["results"].first
      from_attributes(reservation_attributes) if reservation_attributes.present?
    end

    def id
      login
    end

    def self.create(opts)
      date = DateTime.parse(opts[:expires_on]) rescue nil
      body = {
          login: opts[:login],
          type: opts[:type],
          reason: opts[:reason],
          expires_on: date
      }.to_json

      response = post "/reservations", body: body
      response
    end

    def update(opts)
      date = DateTime.parse(opts[:expires_on]) rescue nil
      body = {
          login: opts[:login],
          type: opts[:type],
          reason: opts[:reason],
          expires_on: date
      }.to_json

      response = patch "/reservations", body: body
      response
    end

    def if_user_exists(login)
      response = get "/logins?login=#{login}"

      raise response.body["message"] unless response.success?
      results = response.body["results"]
      results.each do |result|
        if result['type'] == 'User'
          self.instance_variable_set(:@existing_user_id, result['id'])
          return true
        end
      end
      self.instance_variable_set(:@existing_user_id, '')
      false
    end

    def destroy
      response = delete "/reservations/#{login}"

      unless response.success?
        errors.add(:base, response.body.dig("error"))
        return false
      end

      response.success?
    end

  end
end
