require "rails_helper"

describe Public::MaterialReleasesController do
  let(:user)    { create(:user) }
  let(:project) { create(:project, account: user.primary_account) }

  render_views

  describe "#create" do
    it "allows photos param" do
      contract_template = create(:contract_template, project: project)

      post :create, params: { account_id: user.primary_account.to_param, project_id: project, contract_template_id: contract_template, material_release: material_release_params_with_files }

      expect(response).to be_successful
      expect(MaterialRelease.last.files.attached?).to eq true
    end

    it "displays validation errors" do
      contract_template = create(:contract_template, project: project)
      sign_in(user)

      post :create, params: { account_id: user.primary_account.to_param, project_id: project, contract_template_id: contract_template, material_release: { person_address_city: "Albuquerque" } }
      body = CGI.unescape_html(response.body)
      expect(body).to match /Person first name can't be blank/
      expect(body).to match /Person last name can't be blank/
      expect(body).to match />can't be blank</
    end

    it "renders a confirmation page" do
      contract_template = create(:contract_template, project: project)
      post :create, params: { account_id: user.primary_account, project_id: project, contract_template_id: contract_template, material_release: material_release_params }

      expect(response).to be_successful
    end

    it "runs set tags for releasable job" do
      contract_template = create(:contract_template, project: project)

      expect {
        post :create, params: { account_id: project.account.to_param, project_id: project, contract_template_id: contract_template, material_release: material_release_params }
      }.to(
        have_enqueued_job(SetTagsForReleasableJob)
        .with(MaterialRelease.last)
      )
    end

    it "runs attach contract to releasable job" do
      contract_template = create(:contract_template, project: project)

      expect {
        post :create, params: { account_id: project.account.to_param, project_id: project, contract_template_id: contract_template, material_release: material_release_params }
      }.to(
        have_enqueued_job(AttachContractToReleasableJob)
        .with(MaterialRelease.last)
      )
    end
  end

  private

  def material_release_params
    attributes_for(:material_release, :native).except(:signature).merge(signature_param)
  end

  def material_release_params_with_files
    attributes_for(:material_release, :native, :with_file).except(:signature).merge(signature_param)
  end


  def signature_param
    file = file_fixture("signature.png")
    data_uri = Base64Image.from_image(file).data_uri

    { signature_base64: data_uri }
  end
end
