// Copyright 2024 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

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

func TestUncomment(t *testing.T) {
	tests := []struct {
		line     string
		expected string
	}{
		{
			line:     "",
			expected: "",
		},
		{
			line:     "  ",
			expected: "",
		},
		{
			line:     "/* hello  */",
			expected: "hello",
		},
		{
			line:     "// hello ",
			expected: "hello",
		},
	}

	for _, test := range tests {
		r := uncomment(test.line)
		if r != test.expected {
			t.Errorf("uncomment(%q) = %q, expected %q", test.line,
				r, test.expected)
		}
	}
}

func TestWalkAndWrite(t *testing.T) {
	mans := make(map[string]string)
	err := walk(mans, "testdata")
	if err != nil {
		t.Error(err)
	}

	cat, ok := mans["cat"]
	if !ok {
		t.Fatalf("expected to extract manual for cat")
	}

	if !strings.Contains(cat, "cat [-u] [FILES]...") {
		t.Error("missing synopsis")
	}

	if !strings.Contains(cat, "If no files are specified, read from stdin.") {
		t.Error("missing description")
	}

	if !strings.Contains(cat, "-u: ignored flag") {
		t.Error("missing options")
	}

	fn := filepath.Join(t.TempDir(), "dir", "man.go")
	err = writeFile(fn, mans)
	if err != nil {
		t.Fatalf("can't write file: %v", err)
	}

	b, err := os.ReadFile(fn)
	if err != nil {
		t.Errorf("can't read file back")
	}

	content := string(b)

	if !strings.Contains(content, "// Code generated by man/gen/gen.go. DO NOT EDIT.") {
		t.Error("missing comment")
	}

	if !strings.Contains(content, "package data") {
		t.Error("missing package name")
	}

	if !strings.Contains(content, `"{\"cat\":\"cat concatenates`) {
		t.Error("missing json")
	}
}
