defmodule Blogex.PostTest do
  use ExUnit.Case, async: true

  alias Blogex.Post

  describe "build/3" do
    test "extracts date from filename path" do
      post = Post.build("anything/2026/03-10-my-slug.md", valid_attrs(), "<p>body</p>")

      assert post.date == ~D[2026-03-10]
    end

    test "extracts slug from filename" do
      post = Post.build("anything/2026/01-05-cool-feature.md", valid_attrs(), "<p>body</p>")

      assert post.id == "cool-feature"
    end

    test "preserves slug with multiple hyphens" do
      post = Post.build("x/2026/06-01-my-multi-part-slug.md", valid_attrs(), "<p>x</p>")

      assert post.id == "my-multi-part-slug"
    end

    test "merges frontmatter attributes into struct" do
      attrs = %{
        title: "Custom Title",
        author: "Specific Author",
        description: "Custom desc",
        tags: ~w(alpha beta)
      }

      post = Post.build("x/2026/01-01-x.md", attrs, "<p>x</p>")

      assert post.title == "Custom Title"
      assert post.author == "Specific Author"
      assert post.tags == ["alpha", "beta"]
    end

    test "stores rendered HTML body" do
      html = "<h1>Hello</h1><p>World</p>"

      post = Post.build("x/2026/01-01-x.md", valid_attrs(), html)

      assert post.body == html
    end

    test "defaults published to true" do
      post = Post.build("x/2026/01-01-x.md", valid_attrs(), "<p>x</p>")

      assert post.published == true
    end

    test "allows overriding published to false" do
      attrs = Map.put(valid_attrs(), :published, false)

      post = Post.build("x/2026/01-01-x.md", attrs, "<p>x</p>")

      assert post.published == false
    end

    test "preserves image from frontmatter" do
      attrs = Map.put(valid_attrs(), :image, "/images/cover.png")

      post = Post.build("x/2026/01-01-x.md", attrs, "<p>x</p>")

      assert post.image == "/images/cover.png"
    end

    test "defaults image to nil when not in frontmatter" do
      post = Post.build("x/2026/01-01-x.md", valid_attrs(), "<p>x</p>")

      assert post.image == nil
    end
  end

  defp valid_attrs do
    %{
      title: "Title",
      author: "Author",
      description: "Desc",
      tags: ["tag"]
    }
  end
end
