require 'rails_helper'

RSpec.describe 'error responses', type: :request do
  describe 'manual input errors' do
    it 'returns a stable payload for bad requests' do
      get '/tags/name/%20/deerjikists'

      expect(response).to have_http_status(:bad_request)
      expect(json).to include(
          'type' => 'bad_request',
          'message' => be_present,
          'errors' => {},
          'base_errors' => [be_present])
    end

    it 'returns a stable field-error payload for unprocessable requests' do
      member = create(:user, :member)
      tag = create(:tag, :general, name: 'error_response_tag')
      sign_in_as(member)

      patch "/tags/#{ tag.id }", params: { category: 'nico' }

      expect(response).to have_http_status(:unprocessable_entity)
      expect(json).to include(
          'type' => 'validation_error',
          'message' => '入力内容を確認してください．',
          'base_errors' => [])
      expect(json.fetch('errors')).to include(
          'category' => ['ニコタグは変更できません．'])
    end
  end

  describe 'model validation errors' do
    it 'returns field messages for model errors' do
      user = create(:user)
      sign_in_as(user)

      put "/users/#{ user.id }", params: { name: 'a' * 256 }

      expect(response).to have_http_status(:unprocessable_entity)
      expect(json).to include(
          'type' => 'validation_error',
          'message' => '入力内容を確認してください．')
      expect(json.fetch('errors').fetch('name')).to include(be_present)
    end
  end
end
