package main

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestCheckMarkdown(t *testing.T) {
	marker := filepath.Join(t.TempDir(), "must-not-exist")
	source := fmt.Sprintf("# Post\n\n```sh input\ntouch '%s'\ncat <<'END'\nhello\nEND\n```\n", marker)
	source += "\n````md\n```sh input\nif then\n```\n````\n"
	source += "\n```sh output\nif then\n```\n\n```sh\nif then\n```\n"
	source += "\n- Nested example:\n\n  ~~~sh input copy\n  echo nested\n  ~~~\n"
	source += "\n```sh input\nif then\n```\n\n```sh input\necho still-checked\n```\n"
	var diagnostics bytes.Buffer
	checked, failed := checkMarkdown("post.md", []byte(source), &diagnostics)
	if checked != 4 || failed != 1 {
		t.Fatalf("checked=%d failed=%d, diagnostics=%s", checked, failed, &diagnostics)
	}
	opening := strings.LastIndex(source, "```sh input\nif then")
	line := strings.Count(source[:opening], "\n") + 1
	if !strings.Contains(diagnostics.String(), fmt.Sprintf("post.md:%d:", line)) {
		t.Fatalf("missing Markdown location: %s", &diagnostics)
	}
	if _, err := os.Stat(marker); !os.IsNotExist(err) {
		t.Fatalf("shell commands must not execute: %v", err)
	}
}

func TestCheckMarkdownUnterminatedHeredoc(t *testing.T) {
	var diagnostics bytes.Buffer
	checked, failed := checkMarkdown("post.md", []byte("```sh input\nif true; then\ncat <<'END'\nhello\n```\n"), &diagnostics)
	if checked != 1 || failed != 1 {
		t.Fatalf("checked=%d failed=%d, diagnostics=%s", checked, failed, &diagnostics)
	}
}
