defmodule Blogex.BlogIntegrationTest do
  use ExUnit.Case

  describe "compile-time link validation" do
    test "raises LinkError for invalid blog ID in link" do
      tmp_file = Path.join(System.tmp_dir!(), "test_blog_invalid.ex")

      File.write!(tmp_file, """
      defmodule TestBlogInvalidBlogId do
        use Blogex.Blog,
          blog_id: :test,
          app: :blogex,
          from: "priv/blog/test/2026/01-02-invalid-post.md",
          title: "Test Blog",
          base_path: "/blog/test"
      end
      """)

      assert_raise Blogex.LinkError, fn ->
        Code.compile_file(tmp_file, __ENV__.file)
      end

      File.rm!(tmp_file)
    end

    test "raises LinkError for invalid slug in link" do
      tmp_file = Path.join(System.tmp_dir!(), "test_blog_invalid_slug.ex")

      File.write!(tmp_file, """
      defmodule TestBlogInvalidSlug do
        use Blogex.Blog,
          blog_id: :test,
          app: :blogex,
          from: "priv/blog/test/2026/01-02-invalid-post.md",
          title: "Test Blog",
          base_path: "/blog/test"
      end
      """)

      assert_raise Blogex.LinkError, fn ->
        Code.compile_file(tmp_file, __ENV__.file)
      end

      File.rm!(tmp_file)
    end

    test "compiles successfully with valid links" do
      tmp_file = Path.join(System.tmp_dir!(), "test_blog_valid.ex")

      File.write!(tmp_file, """
      defmodule TestBlogValid do
        use Blogex.Blog,
          blog_id: :test,
          app: :blogex,
          from: "priv/blog/test/2026/01-01-valid-post.md",
          title: "Test Blog",
          base_path: "/blog/test"
      end
      """)

      [{TestBlogValid, _bytecode}] = Code.compile_file(tmp_file, __ENV__.file)
      assert TestBlogValid.title() == "Test Blog"

      File.rm!(tmp_file)
    end

    test "LinkError message includes post context" do
      tmp_file = Path.join(System.tmp_dir!(), "test_blog_msg.ex")

      File.write!(tmp_file, """
      defmodule TestBlogErrorMsg do
        use Blogex.Blog,
          blog_id: :test,
          app: :blogex,
          from: "priv/blog/test/2026/01-02-invalid-post.md",
          title: "Test Blog",
          base_path: "/blog/test"
      end
      """)

      exception =
        assert_raise Blogex.LinkError, fn ->
          Code.compile_file(tmp_file, __ENV__.file)
        end

      msg = Exception.message(exception)

      assert msg =~ "invalid internal blog links"
      assert msg =~ "invalid-post"
      assert msg =~ "/blog/unknown/broken"
      assert msg =~ "/blog/engineering/My-Post"

      File.rm!(tmp_file)
    end
  end
end
