# frozen_string_literal: true

require 'rails_helper'

RSpec.describe ReleaseNumber, type: :model do
  let(:project) { create(:project) }

  describe 'value' do
    it 'returns a number corresponding to the order in which the release was signed within the project' do
      later = create(:appearance_release, signed_at: 1.days.ago, project: project)
      earlier = create(:appearance_release, signed_at: 2.day.ago, project: project)

      expect(release_number_for(earlier)).to eq 1
      expect(release_number_for(later)).to eq 2
    end

    it 'does not count other release types' do
      appearance = create(:appearance_release, project: project)
      talent = create(:talent_release, project: project)

      expect(release_number_for(appearance)).to eq 1
      expect(release_number_for(talent)).to eq 1
    end

    it 'returns 1 if there are no saved releases' do
      appearance = build(:appearance_release, project: project)
      expect(release_number_for(appearance)).to eq 1
    end

    it 'does not count releases from other projects' do
      my_appearance = create(:appearance_release, project: project)
      their_appearance = create(:appearance_release, project: build(:project))

      expect(release_number_for(my_appearance)).to eq 1
      expect(release_number_for(their_appearance)).to eq 1
    end

    it 'uses creation timestamp when signed timestamp is not present' do
      third = create(:appearance_release, signed_at: 1.day.ago, created_at: Time.zone.now, project: project)
      second = create(:appearance_release, signed_at: nil, created_at: 2.days.ago, project: project)
      first = create(:appearance_release, signed_at: 3.days.ago, created_at: Time.zone.now, project: project)

      expect(release_number_for(first)).to eq 1
      expect(release_number_for(second)).to eq 2
      expect(release_number_for(third)).to eq 3
    end
  end

  private

  def release_number_for(release)
    ReleaseNumber.new(release).value
  end
end
