package template

import (
	"embed"
	"fmt"
	"strings"

	domtpl "gateway/internal/model/notification/domain/template"
)

//go:embed subjects/*.txt html/*.html sms/*.txt
var embeddedFS embed.FS

func readEmbeddedTemplate(path string) (string, error) {
	path = strings.TrimPrefix(path, "/")
	b, err := embeddedFS.ReadFile(path)
	if err != nil {
		return "", fmt.Errorf("template: read %q: %w", path, err)
	}
	return string(b), nil
}

// resolveSpec loads embedded files into executable template strings.
func resolveSpec(spec domtpl.Spec) (subject, body, sms string, err error) {
	switch {
	case spec.EmailSubjectFile != "":
		subject, err = readEmbeddedTemplate(spec.EmailSubjectFile)
		if err != nil {
			return "", "", "", err
		}
	default:
		subject = spec.EmailSubject
	}

	switch {
	case spec.EmailBodyFile != "":
		body, err = readEmbeddedTemplate(spec.EmailBodyFile)
		if err != nil {
			return "", "", "", err
		}
	default:
		body = spec.EmailBody
	}

	switch {
	case spec.SMSTextFile != "":
		sms, err = readEmbeddedTemplate(spec.SMSTextFile)
		if err != nil {
			return "", "", "", err
		}
	default:
		sms = spec.SMSText
	}

	return subject, body, sms, nil
}
