require "rails_helper"

RSpec.describe MedicalRelease do
  it_behaves_like "a contractable"
  it_behaves_like "a notable"
  it_behaves_like "a photoable"
  it_behaves_like "a releasable"

  describe "validations" do
    it { is_expected.to validate_presence_of(:person_first_name) }
    it { is_expected.to validate_presence_of(:person_last_name) }

    context "for #person_email" do
      it { is_expected.to allow_value("test@test.com", nil).for(:person_email) }
      it { is_expected.not_to allow_values("foo", "test@foo", "N/A").for(:person_email) }
    end

    context "for native releases" do
      it { is_expected.to validate_attachment_of(:signature).on(:native) }
    end

    context "for non-native releases" do
      it { is_expected.to validate_attachment_of(:contract).on(:non_native) }
    end

    context "question answers" do
      let(:project) { create(:project) }
      let(:contract_template) { create(:contract_template, project: project, question_1_text: 'Question 1') }

      it "returns validation errors if answers are missing" do
        expect do
          create(:medical_release, contract_template: contract_template)
        end.to raise_exception ActiveRecord::RecordInvalid
      end

      it "creates release if answers are present" do
        expect do
          create(:medical_release, contract_template: contract_template, question_1_answer: 'Answer 1')
        end.to change(MedicalRelease, :count).by(1)
      end
    end
  end

  describe "attachments" do
    it { is_expected.to respond_to(:signature) }
  end

  describe "#uses_edl?" do
    it { is_expected.not_to be_uses_edl }
  end

  describe "#contract_file_name" do
    it "includes project name, signed at date, release type, release number and person name" do
      release = create(:medical_release_with_contract_template, id: 100, signed_at: Date.new(2020, 2, 10), person_first_name: "John", person_last_name: "Doe")

      expect(release.contract_file_name).to eq("my-video-project_medical_2020.02.10_1_doe-john")
    end

    context "when signed at is nil" do
      it "uses the created at date" do
        release = create(:medical_release_with_contract_template, 
                         signed_at: nil, 
                         created_at: DateTime.new(2020, 2, 10, 12, 0, 0), 
                         person_first_name: "John", person_last_name: "Doe")

        expect(release.contract_file_name).to eq("my-video-project_medical_2020.02.10_1_doe-john")
      end
    end
  end
end
