require 'rails_helper'

RSpec.describe TagImplication, type: :model do
  it 'rejects a parent tag that would create a cycle' do
    child = create(:tag, name: 'tag_implication_cycle_child')
    parent = create(:tag, name: 'tag_implication_cycle_parent')

    described_class.create!(tag: child, parent_tag: parent)

    implication = described_class.new(tag: parent, parent_tag: child)

    expect(implication).not_to be_valid
    expect(implication.errors[:parent_tag_id]).to include(
      '親タグに子孫タグを指定すると循環します．'
    )
    expect(implication.errors[:base]).to be_present
  end

  it 'terminates even when existing data already contains a cycle' do
    child = create(:tag, name: 'tag_implication_existing_cycle_child')
    parent = create(:tag, name: 'tag_implication_existing_cycle_parent')
    ancestor = create(:tag, name: 'tag_implication_existing_cycle_ancestor')

    described_class.create!(tag: parent, parent_tag: ancestor)
    described_class.insert_all!(
      [
        { tag_id: ancestor.id, parent_tag_id: parent.id,
          created_at: Time.current, updated_at: Time.current }
      ]
    )

    implication = described_class.new(tag: child, parent_tag: parent)

    expect(implication).to be_valid
  end
end
