require_relative "test_helper"

class RepositoryTest < Minitest::Test
  include AdrTestHelpers

  def test_next_id_on_empty_dir_is_0001
    with_project do |root|
      assert_equal "0001", Adr::Repository.new(root: root).next_id
    end
  end

  def test_next_id_is_max_plus_one
    with_project("0001-a.md" => sample_adr(id: "0001"),
                 "0002-b.md" => sample_adr(id: "0002")) do |root|
      assert_equal "0003", Adr::Repository.new(root: root).next_id
    end
  end

  def test_next_id_ignores_missing_index
    with_project("0007-x.md" => sample_adr(id: "0007")) do |root|
      repo = Adr::Repository.new(root: root)
      refute File.exist?(repo.index_path)
      assert_equal "0008", repo.next_id
    end
  end

  def test_next_id_ignores_stale_index
    with_project("0007-x.md" => sample_adr(id: "0007")) do |root|
      repo = Adr::Repository.new(root: root)
      File.write(repo.index_path, "| 0042 | stale row |")
      assert_equal "0008", repo.next_id
    end
  end

  def test_exists_requires_dir_and_index
    with_project do |root|
      repo = Adr::Repository.new(root: root)
      refute repo.exists?
      File.write(repo.index_path, "index")
      assert repo.exists?
    end
    Dir.mktmpdir do |root|
      refute Adr::Repository.new(root: root).exists?
    end
  end

  def test_find_by_id
    with_project("0002-b.md" => sample_adr(id: "0002", title: "B")) do |root|
      entry = Adr::Repository.new(root: root).find("0002")
      assert_equal "B", entry.record.title
      assert entry.path.end_with?("0002-b.md")
    end
  end

  def test_non_adr_files_are_ignored
    with_project("0001-a.md" => sample_adr, "notes.md" => "# notes") do |root|
      repo = Adr::Repository.new(root: root)
      assert_equal 1, repo.entries.size
      assert_equal "0002", repo.next_id
    end
  end
end
