package cli

import (
	"os"
	"path/filepath"
	"testing"
)

func TestReadWritePostFile(t *testing.T) {
	dir := t.TempDir()
	publishedAt := "2026-05-28T12:00:00+08:00"
	post := postFile{
		Path: filepath.Join(dir, "hello.md"),
		Frontmatter: postFrontmatter{
			ID:          "post-1",
			Slug:        "hello",
			Title:       "Hello",
			Summary:     "Summary",
			Status:      "published",
			Tags:        []string{"go", "astro"},
			Version:     2,
			SlugSource:  "manual",
			PublishedAt: &publishedAt,
			CreatedAt:   "2026-05-28T11:00:00+08:00",
			UpdatedAt:   "2026-05-28T12:00:00+08:00",
		},
		Body: "Body\n",
	}

	if err := writePostFile(post); err != nil {
		t.Fatal(err)
	}

	got, err := readPostFile(post.Path)
	if err != nil {
		t.Fatal(err)
	}
	if got.Frontmatter.ID != post.Frontmatter.ID || got.Frontmatter.Slug != post.Frontmatter.Slug {
		t.Fatalf("frontmatter mismatch: %#v", got.Frontmatter)
	}
	if got.Body != post.Body {
		t.Fatalf("body = %q, want %q", got.Body, post.Body)
	}
	if len(got.Frontmatter.Tags) != 2 || got.Frontmatter.Tags[1] != "astro" {
		t.Fatalf("tags = %#v", got.Frontmatter.Tags)
	}
}

func TestReadPostFileRequiresFrontmatter(t *testing.T) {
	path := filepath.Join(t.TempDir(), "bad.md")
	if err := os.WriteFile(path, []byte("no frontmatter"), 0o644); err != nil {
		t.Fatal(err)
	}
	if _, err := readPostFile(path); err == nil {
		t.Fatal("expected frontmatter error")
	}
}
