require 'rails_helper'

RSpec.describe Dunlop::TargetFilesController do
  routes { Dunlop::Engine.routes }
  before { sign_in user}
  describe 'authorized' do
    let(:user) { create :user, role_names: ['manage-model-target-file/my-target'] }
    describe '#download' do
      it "downloads the model and logs it" do
        model = create 'target_file/my_target'
        model.execute_generation_process
        get :download, params: {id: model.id}
        response.should be_ok
        response.headers['Content-Disposition'].should start_with 'attachment; filename="my_target-'
        response.headers['Content-Disposition'].should end_with '.csv.gz"'

        download = Dunlop::FileDownload.last
        download.user.should eq user
        download.file.should eq model
      end
    end

    describe '#download_latest' do
      it "downloads the latest model and logs it" do
        model = create 'target_file/my_target'
        model.execute_generation_process
        get :download_latest, params: {target_file_type: 'my_target'}
        response.should be_ok
        response.headers['Content-Disposition'].should start_with 'attachment; filename="my_target-'
        response.headers['Content-Disposition'].should end_with '.csv.gz"'

        download = Dunlop::FileDownload.last
        download.user.should eq user
        download.file.should eq model
      end
    end
  end

  describe 'unauthorized' do
    let(:user) { create :user, role_names: [] }
    describe '#download' do
      it "403" do
        model = create 'target_file/my_target'
        model.execute_generation_process
        get :download, params: {id: model.id}
        response.status.should eq 403
      end
    end

    describe '#download_latest' do
      it "403" do
        model = create 'target_file/my_target'
        model.execute_generation_process
        get :download_latest, params: {target_file_type: 'my_target'}
        response.status.should eq 403
      end
    end
  end
end
