package formgenerator

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

//go:embed templates/index.html
var formTemplate string

//go:embed templates
var formFS embed.FS

var (
	requiredFields []string = []string{
		"VacancyName",
		"Address",
		"WorkFormat",
		"SalaryTop",
		"SalaryBottom",
		"Requirements",
		"Responsibilities",
		"Description",

		"VacancyId",
		"AgentId",
	}
)

var (
	ErrNotFound = errors.New("One of the required fields is not set")
)

func GetFileSystem() (fs.FS, error) {
	formFs, err := fs.Sub(formFS, "templates")
	if err != nil {
		return nil, err
	}

	return formFs, nil
}

func GenerateForm(formData map[string]string) (string, error) {
	for _, field := range requiredFields {
		if _, ok := formData[field]; !ok {
			return "", ErrNotFound
		}
	}

	tmpl, err := template.New("index.html").Parse(formTemplate)
	if err != nil {
		return "", err
	}

	var buf strings.Builder

	if err = tmpl.Execute(&buf, formData); err != nil {
		return "", err
	}

	return buf.String(), nil
}
