require 'spec_helper'

describe USER_APP do
  def app
    USER_APP
  end

  def post_json(uri, json)
    post(uri, json, { "CONTENT_TYPE" => "application/json" })
  end

  after :each do
    puts "Response was:"
    puts "Status: #{last_response.status}"
    puts "Body:"
    puts "#{last_response.body.lines.first(20).join('')}"
  end

  context 'when posting to invalid path' do
    before :each do
      post '/'
    end

    it 'responds with 404' do
      expect(last_response.status).to eq(404)
    end
  end

  context 'a valid post to signup' do
    before :each do
      data = {
        username: 'goserv',
        email: 'goserv@goserv.com',
        password: 'g0s3rv3r'
      }
      post_json '/signup', data.to_json
    end

    it 'responds with 200' do
      expect(last_response.status).to eq(200)
    end

    it 'responds with SUCCESS body' do
      expect(JSON.parse(last_response.body)['code']).to eq('SUCCESS')
    end

    it 'creates a user' do
      expect(GoUser::User.where(username: 'goserv')).not_to be_empty
    end
  end

  context 'an existing user to signup' do
    before :each do
      data = {
        username: 'goserv',
        email: 'goserv@goserv.com',
        password: 'g0s3rv3r'
      }
      GoUser.create_user(**data)
      post_json '/signup', data.to_json
      @resp_body = JSON.parse(last_response.body)
    end

    it 'responds with 409' do
      expect(last_response.status).to eq(409)
    end

    it 'responds with USER_INVALID body' do
      expect(@resp_body['code']).to eq('USER_INVALID')
    end

    it 'has error messages' do
      expect(@resp_body['errors']).not_to be_empty
    end
  end

  context 'an invalid email to signup' do
    before :context do
      data = {
        username: 'goserv',
        email: 'goserv',
        password: 'g0s3rv3r'
      }
      post_json '/signup', data.to_json
      @resp_body = JSON.parse(last_response.body)
    end

    it 'responds with 400' do
      expect(last_response.status).to eq(400)
    end

    it 'responds with SCHEMA_VALIDATION body' do
      expect(@resp_body['code']).to eq('SCHEMA_VALIDATION')
    end

    it 'has error messages' do
      expect(@resp_body['errors']).not_to be_empty
    end
  end
end
