package site

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

func TestBuildHiddenPostsRenderButDoNotList(t *testing.T) {
	root := t.TempDir()
	contentDir := filepath.Join(root, "content")
	staticDir := filepath.Join(root, "static")
	outDir := filepath.Join(root, "public")
	cfgPath := filepath.Join(root, "config.yaml")

	for _, dir := range []string{contentDir, staticDir} {
		if err := os.MkdirAll(dir, 0o755); err != nil {
			t.Fatal(err)
		}
	}

	configYAML := `title: "Test Blog"
hostname: "test.local"
theme: "default"
`
	if err := os.WriteFile(cfgPath, []byte(configYAML), 0o644); err != nil {
		t.Fatal(err)
	}

	visiblePost := `---
title: "Visible Post"
date: 2026-04-08
tags:
  - visible
---

Visible body.
`
	hiddenPost := `---
title: "Hidden Post"
date: 2026-04-09
hidden: true
tags:
  - hidden-tag
---

Hidden body.
`
	draftPost := `---
title: "Draft Post"
date: 2026-04-10
draft: true
---

Draft body.
`
	if err := os.WriteFile(filepath.Join(contentDir, "visible-post.md"), []byte(visiblePost), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(contentDir, "hidden-post.md"), []byte(hiddenPost), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(contentDir, "draft-post.md"), []byte(draftPost), 0o644); err != nil {
		t.Fatal(err)
	}

	res, err := Build(BuildOptions{
		ConfigPath: cfgPath,
		ContentDir: contentDir,
		StaticDir:  staticDir,
		ThemesDir:  filepath.Join("..", "..", "themes"),
		OutDir:     outDir,
	})
	if err != nil {
		t.Fatalf("Build returned error: %v", err)
	}
	if res.PostCount != 2 {
		t.Fatalf("expected 2 rendered posts, got %d", res.PostCount)
	}
	if res.TagCount != 1 {
		t.Fatalf("expected 1 listed tag, got %d", res.TagCount)
	}

	assertFileContains(t, filepath.Join(outDir, "blog", "hidden-post", "index.html"), "Hidden Post")
	assertFileContains(t, filepath.Join(outDir, "blog", "visible-post", "index.html"), "Visible Post")
	assertFileMissing(t, filepath.Join(outDir, "hidden-post", "index.html"))
	assertFileMissing(t, filepath.Join(outDir, "visible-post", "index.html"))
	assertFileMissing(t, filepath.Join(outDir, "blog", "draft-post", "index.html"))
	assertFileMissing(t, filepath.Join(outDir, "draft-post", "index.html"))

	assertFileContains(t, filepath.Join(outDir, "index.html"), "/blog/")

	assertFileContains(t, filepath.Join(outDir, "blog", "index.html"), "visible-post.md")
	assertFileContains(t, filepath.Join(outDir, "blog", "index.html"), `href="/blog/visible-post/"`)
	assertFileNotContains(t, filepath.Join(outDir, "blog", "index.html"), "hidden-post.md")
	assertFileNotContains(t, filepath.Join(outDir, "blog", "index.html"), "draft-post.md")

	assertFileContains(t, filepath.Join(outDir, "tags", "index.html"), "visible")
	assertFileContains(t, filepath.Join(outDir, "tags", "visible", "index.html"), `href="/blog/visible-post/"`)
	assertFileNotContains(t, filepath.Join(outDir, "tags", "index.html"), "hidden-tag")
	assertFileMissing(t, filepath.Join(outDir, "tags", "hidden-tag", "index.html"))

	assertFileContains(t, filepath.Join(outDir, "archives", "2026", "index.html"), "visible-post.md")
	assertFileContains(t, filepath.Join(outDir, "archives", "2026", "index.html"), `href="/blog/visible-post/"`)
	assertFileNotContains(t, filepath.Join(outDir, "archives", "2026", "index.html"), "hidden-post.md")
	assertFileContains(t, filepath.Join(outDir, "blog", "visible-post", "index.html"), `href="/blog/visible-post/"`)
	assertFileContains(t, filepath.Join(outDir, "blog", "hidden-post", "index.html"), "/tags/hidden-tag/")
	assertFileContains(t, filepath.Join(outDir, "blog", "hidden-post", "index.html"), `href="/blog/visible-post/"`)
}

func TestBuildListingTimeUsesFrontMatterTimeWhenPresent(t *testing.T) {
	root := t.TempDir()
	contentDir := filepath.Join(root, "content")
	staticDir := filepath.Join(root, "static")
	outDir := filepath.Join(root, "public")
	cfgPath := filepath.Join(root, "config.yaml")

	for _, dir := range []string{contentDir, staticDir} {
		if err := os.MkdirAll(dir, 0o755); err != nil {
			t.Fatal(err)
		}
	}

	configYAML := `title: "Test Blog"
hostname: "test.local"
theme: "default"
`
	if err := os.WriteFile(cfgPath, []byte(configYAML), 0o644); err != nil {
		t.Fatal(err)
	}

	path := filepath.Join(contentDir, "timed-post.md")
	post := `---
title: "Timed Post"
date: 2026-04-08T14:30:00
---

Timed body.
`
	if err := os.WriteFile(path, []byte(post), 0o644); err != nil {
		t.Fatal(err)
	}
	modTime := time.Date(2026, 4, 8, 9, 5, 0, 0, time.UTC)
	if err := os.Chtimes(path, modTime, modTime); err != nil {
		t.Fatal(err)
	}

	if _, err := Build(BuildOptions{
		ConfigPath: cfgPath,
		ContentDir: contentDir,
		StaticDir:  staticDir,
		ThemesDir:  filepath.Join("..", "..", "themes"),
		OutDir:     outDir,
	}); err != nil {
		t.Fatalf("Build returned error: %v", err)
	}

	assertFileContains(t, filepath.Join(outDir, "blog", "index.html"), "14:30")
	assertFileNotContains(t, filepath.Join(outDir, "blog", "index.html"), "09:05")
}

func TestBuildRejectsOutputInsideInputRoots(t *testing.T) {
	root := t.TempDir()
	contentDir := filepath.Join(root, "content")
	staticDir := filepath.Join(root, "static")
	themesDir := filepath.Join(root, "themes")
	cfgPath := filepath.Join(root, "config.yaml")
	makeBuildFixture(t, contentDir, staticDir, themesDir, cfgPath)

	cases := []struct {
		name   string
		outDir string
	}{
		{name: "static root", outDir: staticDir},
		{name: "inside static root", outDir: filepath.Join(staticDir, "public")},
		{name: "content root", outDir: contentDir},
		{name: "inside content root", outDir: filepath.Join(contentDir, "public")},
		{name: "theme root", outDir: filepath.Join(themesDir, "default")},
		{name: "inside theme root", outDir: filepath.Join(themesDir, "default", "public")},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			_, err := Build(BuildOptions{
				ConfigPath: cfgPath,
				ContentDir: contentDir,
				StaticDir:  staticDir,
				ThemesDir:  themesDir,
				OutDir:     tc.outDir,
			})
			if err == nil {
				t.Fatalf("expected error for output dir %s", tc.outDir)
			}
			if !strings.Contains(err.Error(), "invalid output directory") {
				t.Fatalf("unexpected error: %v", err)
			}
		})
	}
}

func makeBuildFixture(t *testing.T, contentDir, staticDir, themesDir, cfgPath string) {
	t.Helper()
	for _, dir := range []string{
		contentDir,
		staticDir,
		filepath.Join(themesDir, "default", "layouts"),
		filepath.Join(themesDir, "default", "partials"),
		filepath.Join(themesDir, "default", "assets"),
	} {
		if err := os.MkdirAll(dir, 0o755); err != nil {
			t.Fatal(err)
		}
	}
	configYAML := `title: "Test Blog"
hostname: "test.local"
theme: "default"
`
	if err := os.WriteFile(cfgPath, []byte(configYAML), 0o644); err != nil {
		t.Fatal(err)
	}
	post := `---
title: "Visible Post"
date: 2026-04-08
---

Visible body.
`
	if err := os.WriteFile(filepath.Join(contentDir, "visible-post.md"), []byte(post), 0o644); err != nil {
		t.Fatal(err)
	}
	layouts := map[string]string{
		"index":         `{{define "index"}}home{{end}}`,
		"blog":          `{{define "blog"}}blog{{end}}`,
		"tags":          `{{define "tags"}}tags{{end}}`,
		"archives":      `{{define "archives"}}archives{{end}}`,
		"404":           `{{define "404"}}not found{{end}}`,
		"post":          `{{define "post"}}{{.Post.Title}}{{end}}`,
		"tag":           `{{define "tag"}}tag{{end}}`,
		"archive_year":  `{{define "archive_year"}}year{{end}}`,
		"archive_month": `{{define "archive_month"}}month{{end}}`,
	}
	for name, body := range layouts {
		if err := os.WriteFile(filepath.Join(themesDir, "default", "layouts", name+".html"), []byte(body), 0o644); err != nil {
			t.Fatal(err)
		}
	}
	if err := os.WriteFile(filepath.Join(staticDir, "asset.txt"), []byte("asset"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(themesDir, "default", "assets", "style.css"), []byte("body{}"), 0o644); err != nil {
		t.Fatal(err)
	}
}

func TestExcerptHTMLUsesFirstTwoParagraphSentences(t *testing.T) {
	t.Parallel()
	body := `<h1>Repeated title</h1><p>First <strong>sentence</strong>.</p><p>Second sentence! Third sentence.</p>`
	if got, want := excerptHTML(body), "First sentence. Second sentence!"; got != want {
		t.Fatalf("excerptHTML() = %q, want %q", got, want)
	}
}

func assertFileContains(t *testing.T, path, want string) {
	t.Helper()
	b, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read %s: %v", path, err)
	}
	if !strings.Contains(string(b), want) {
		t.Fatalf("%s does not contain %q", path, want)
	}
}

func assertFileNotContains(t *testing.T, path, want string) {
	t.Helper()
	b, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read %s: %v", path, err)
	}
	if strings.Contains(string(b), want) {
		t.Fatalf("%s unexpectedly contains %q", path, want)
	}
}

func assertFileMissing(t *testing.T, path string) {
	t.Helper()
	if _, err := os.Stat(path); !os.IsNotExist(err) {
		t.Fatalf("expected %s to be missing, got err=%v", path, err)
	}
}
