require_relative "test_helper"

class IndexTest < Minitest::Test
  include AdrTestHelpers

  GOLDEN = <<~MD
    <!-- Generated by os-adr. Do not hand-edit the table: it is regenerated in full on every ADR write. -->

    # Architecture Decision Records

    One file per decision, `NNNN-kebab-title.md`, created via `/os-adr:create`.

    <!-- adr-index:begin -->
    | ID | Title | Status | Date |
    | --- | --- | --- | --- |
    | 0001 | [Use Postgres](0001-use-postgres.md) | Accepted | 2026-07-03 |
    | 0002 | [Use Redis](0002-use-redis.md) | Accepted | 2026-07-03 |
    <!-- adr-index:end -->
  MD

  def two_adr_project(&block)
    with_project("0001-use-postgres.md" => sample_adr(id: "0001", title: "Use Postgres"),
                 "0002-use-redis.md" => sample_adr(id: "0002", title: "Use Redis"), &block)
  end

  def test_regenerates_full_table_matching_golden
    two_adr_project do |root|
      repo = Adr::Repository.new(root: root)
      Adr::Index.new(repository: repo).regenerate!
      assert_equal GOLDEN, File.read(repo.index_path)
    end
  end

  def test_self_heals_after_manual_table_edit
    two_adr_project do |root|
      repo = Adr::Repository.new(root: root)
      index = Adr::Index.new(repository: repo)
      index.regenerate!
      vandalized = File.read(repo.index_path)
        .sub("| 0001 | [Use Postgres](0001-use-postgres.md) | Accepted | 2026-07-03 |\n", "")
        .sub("Use Redis", "Hand-Edited Title")
      File.write(repo.index_path, vandalized)
      index.regenerate!
      assert_equal GOLDEN, File.read(repo.index_path)
    end
  end

  def test_preserves_prose_outside_markers
    two_adr_project do |root|
      repo = Adr::Repository.new(root: root)
      index = Adr::Index.new(repository: repo)
      index.regenerate!
      File.write(repo.index_path, "Custom preamble.\n\n" + File.read(repo.index_path) + "\nCustom footer.\n")
      index.regenerate!
      content = File.read(repo.index_path)
      assert_includes content, "Custom preamble."
      assert_includes content, "Custom footer."
      assert_includes content, "| 0001 | [Use Postgres](0001-use-postgres.md) | Accepted | 2026-07-03 |"
    end
  end

  def test_empty_directory_yields_empty_table
    with_project do |root|
      repo = Adr::Repository.new(root: root)
      Adr::Index.new(repository: repo).regenerate!
      content = File.read(repo.index_path)
      assert_includes content, Adr::Index::BEGIN_MARKER
      refute_includes content, "| ID |"
    end
  end

  def test_index_declares_itself_generated
    with_project do |root|
      repo = Adr::Repository.new(root: root)
      Adr::Index.new(repository: repo).regenerate!
      assert_match(/do not hand-edit/i, File.read(repo.index_path))
    end
  end
end
