package templates

import (
	"embed"
	"fmt"
	"html/template"
	"io/fs"
	"strings"
)

//go:embed static/*
var static embed.FS

const fileType = ".gohtml"

// Parse walks the embedded static directory and parses all .gohtml templates.
func Parse() (*template.Template, error) {
	tmpl := template.New("")

	parseFS := func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if d.IsDir() {
			return nil
		}
		if strings.Contains(path, fileType) {
			if _, err := tmpl.ParseFS(static, path); err != nil {
				return fmt.Errorf(
					"failed to parse template %s: %w",
					path, err,
				)
			}
		}
		return nil
	}

	if err := fs.WalkDir(static, ".", parseFS); err != nil {
		return nil, fmt.Errorf("failed to parse templates: %w", err)
	}

	return tmpl, nil
}
