require "rails_helper"

RSpec.describe TalentRelease do
  it_behaves_like "a contractable"
  it_behaves_like "an exploitable"
  it_behaves_like "a notable"
  it_behaves_like "a photoable"
  it_behaves_like "a releasable"
  it_behaves_like "a taggable"

  describe "associations" do
    it { is_expected.to have_many(:video_release_confirmations).dependent(:destroy) }
    it { is_expected.to have_many(:confirmed_videos).source(:video).through(:video_release_confirmations) }
  end

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

    it "requires one or more photo" do
      talent_release = build(:talent_release, photos: [])
      expect(talent_release).not_to be_valid
      expect(talent_release.errors[:photos]).to include("must be included")
    end

    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_presence_of(:person_phone).on(:native) }
      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 "when the signer is a minor" do
      subject { build(:talent_release, :minor) }

      it { is_expected.to validate_presence_of(:guardian_first_name) }
      it { is_expected.to validate_presence_of(:guardian_last_name) }
      it { is_expected.to validate_presence_of(:guardian_phone) }
    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(:talent_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_talent_2020.02.10_1_doe-john")
    end

    context "when signed at is nil" do
      it "uses the created at date" do
        release = create(:talent_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_talent_2020.02.10_1_doe-john")
      end
    end
  end
end
