require 'rails_helper'


RSpec.describe 'Preview', type: :request do
  describe 'GET /preview/title' do
    it '401 unless logged in' do
      sign_out
      get '/preview/title', params: { url: 'example.com' }
      expect(response).to have_http_status(:unauthorized)
    end

    it '403 when logged in as guest' do
      sign_in_as(create(:user, :guest))
      get '/preview/title', params: { url: 'example.com' }
      expect(response).to have_http_status(:forbidden)
    end

    it '400 when url blank' do
      sign_in_as(create(:user, :member))
      get '/preview/title', params: { url: '' }
      expect(response).to have_http_status(:bad_request)
    end

    it 'returns parsed title' do
      sign_in_as(create(:user, :member))
      allow(Preview::ThumbnailFetcher)
          .to receive(:title)
          .with('example.com')
          .and_return('Hello')

      get '/preview/title', params: { url: 'example.com' }
      expect(response).to have_http_status(:ok)
      expect(json['title']).to eq('Hello')
    end

    it '413 when fetched response is too large' do
      sign_in_as(create(:user, :member))
      allow(Preview::ThumbnailFetcher)
          .to receive(:title)
          .and_raise(Preview::HttpFetcher::ResponseTooLarge, '外部データが大きすぎます．')

      get '/preview/title', params: { url: 'example.com' }
      expect(response).to have_http_status(:payload_too_large)
    end
  end
end
