# frozen_string_literal: true

require 'rails_helper'

RSpec.describe Api::UserTokenController, type: :request do
  let(:current_user) { create(:user) }

  describe '#create' do
    it 'returns error if credentials are not corrent and does not set cookie' do

      post create_endpoint, params: wrong_auth_params

      expect(response).to be_successful
      expect(response.body).to match record_not_found
      expect(cookie_data).to eq nil
    end

    it 'sends token and cookie if credentials are correct' do
      post create_endpoint, params: correct_auth_params

      expect(response).to be_successful
      expect(response.body).not_to match record_not_found
      expect(response.body).to match token_response
      expect(cookie_data).not_to eq nil
    end
  end

  private

  def wrong_auth_params
    {
      auth: {
        email: 'wrong_email@api-test.com',
        password: 'password'
      }
    }
  end

  def correct_auth_params
    {
      auth: {
        email: current_user.email,
        password: 'password'
      }
    }
  end

  def create_endpoint
    '/api/v1/user_token'
  end

  def record_not_found
    /Record not found/
  end

  def token_response
    /jwt/
  end

  def cookie_data
    cookies[:_easy_release_session]
  end
end
