require 'rails_helper'

RSpec.describe 'Measurements', type: :request do
  # initialize test data
  let(:user) { create(:user) }
  let(:measure) { create(:measure) }
  let!(:measurements) { create_list(:measurement, 10, user_id: user.id, measure_id: measure.id) }
  let(:measurement_id) { measurements.first.id }
  # authorize request
  let(:headers) { valid_headers }

  # Test suite for GET /measurements
  describe 'GET /measurements' do
    # make HTTP get request before each example
    # update request with headers
    before { get '/measurements', params: {}, headers: headers }

    it 'returns measurements' do
      # Note `json` is a custom helper to parse JSON responses
      expect(json).not_to be_empty
      expect(json.size).to eq(10)
    end

    it 'returns status code 200' do
      expect(response).to have_http_status(200)
    end
  end

  # # Test suite for GET /measurements/:id
  # describe 'GET /measurements/:id' do
  #   before { get "/measurements/#{measurement_id}", params: {}, headers: headers }

  #   context 'when the record exists' do
  #     it 'returns the measurement' do
  #       expect(json).not_to be_empty
  #       expect(json['id']).to eq(measurement_id)
  #     end

  #     it 'returns status code 200' do
  #       expect(response).to have_http_status(200)
  #     end
  #   end

  #   context 'when the record does not exist' do
  #     let(:measurement_id) { 100 }

  #     it 'returns status code 404' do
  #       expect(response).to have_http_status(404)
  #     end

  #     it 'returns a not found message' do
  #       expect(response.body).to match(/Couldn't find Measurement/)
  #     end
  #   end
  # end

  # Test suite for POST /measurements
  describe 'POST /measurements' do
    # valid payload
    let(:valid_attributes) do
      # send json payload
      { measurements: [{ value: 23, user_id: user.id, measure_id: measure.id }] }.to_json
    end

    context 'when the request is valid' do
      before { post '/measurements', params: valid_attributes, headers: headers }

      it 'creates a measurement' do
        expect(json[0]['value']).to eq(23)
      end

      it 'returns status code 201' do
        expect(response).to have_http_status(201)
      end
    end

    context 'when the request is invalid' do
      let(:invalid_attributes) { { value: nil }.to_json }
      before { post '/measurements', params: invalid_attributes, headers: headers }

      it 'returns status code 422' do
        expect(response).to have_http_status(422)
      end

      it 'returns a validation failure message' do
        expect(json['message'])
          .to match(/Validation failed: Measure must exist, Value can't be blank/)
      end
    end
  end
end
