package template

import (
	"fmt"

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

// DefaultRegistry returns built-in templates (content loaded from go:embed files).
func DefaultRegistry() domtpl.Registry {
	return domtpl.Registry{
		enum.NotifyVerifyEmail: localeSpecs(otpEmailVars(),
			emailFiles("verify_email"),
			nil,
		),
		enum.NotifyVerifyRegistrationEmail: localeSpecs(otpEmailVars(),
			emailFiles("verify_registration_email"),
			nil,
		),
		enum.NotifyVerifyPhone: localeSpecs(otpSMSVars(),
			nil,
			smsFiles("verify_phone"),
		),
		enum.NotifyStepUpEmail: localeSpecs(otpEmailVars(),
			emailFiles("step_up_email"),
			nil,
		),
		enum.NotifyStepUpPhone: localeSpecs(otpSMSVars(),
			nil,
			smsFiles("step_up_phone"),
		),
		enum.NotifyAccountSuspended: {
			domtpl.LocaleZhTW: {
				RequiredVars:     []string{},
				EmailSubjectFile: fmt.Sprintf("subjects/account_suspended.%s.txt", domtpl.LocaleZhTW),
				EmailBodyFile:    fmt.Sprintf("html/account_suspended.%s.html", domtpl.LocaleZhTW),
			},
		},
		enum.NotifyTenantWelcome: {
			domtpl.LocaleZhTW: {
				RequiredVars:     []string{"tenant_name"},
				EmailSubjectFile: fmt.Sprintf("subjects/tenant_welcome.%s.txt", domtpl.LocaleZhTW),
				EmailBodyFile:    fmt.Sprintf("html/tenant_welcome.%s.html", domtpl.LocaleZhTW),
			},
		},
	}
}

func otpEmailVars() []string { return []string{domtpl.VarCode, domtpl.VarExpiresIn} }
func otpSMSVars() []string   { return []string{domtpl.VarCode, domtpl.VarExpiresIn} }

func emailFiles(base string) map[string]domtpl.Spec {
	return map[string]domtpl.Spec{
		domtpl.LocaleZhTW: {
			EmailSubjectFile: fmt.Sprintf("subjects/%s.%s.txt", base, domtpl.LocaleZhTW),
			EmailBodyFile:    fmt.Sprintf("html/%s.%s.html", base, domtpl.LocaleZhTW),
		},
		domtpl.LocaleEnUS: {
			EmailSubjectFile: fmt.Sprintf("subjects/%s.%s.txt", base, domtpl.LocaleEnUS),
			EmailBodyFile:    fmt.Sprintf("html/%s.%s.html", base, domtpl.LocaleEnUS),
		},
	}
}

func smsFiles(base string) map[string]domtpl.Spec {
	return map[string]domtpl.Spec{
		domtpl.LocaleZhTW: {SMSTextFile: fmt.Sprintf("sms/%s.%s.txt", base, domtpl.LocaleZhTW)},
		domtpl.LocaleEnUS: {SMSTextFile: fmt.Sprintf("sms/%s.%s.txt", base, domtpl.LocaleEnUS)},
	}
}

func localeSpecs(required []string, email, sms map[string]domtpl.Spec) map[string]domtpl.Spec {
	locales := []string{domtpl.LocaleZhTW, domtpl.LocaleEnUS}
	out := make(map[string]domtpl.Spec, len(locales))
	for _, loc := range locales {
		spec := domtpl.Spec{RequiredVars: required}
		if email != nil {
			if e, ok := email[loc]; ok {
				spec.EmailSubjectFile = e.EmailSubjectFile
				spec.EmailBodyFile = e.EmailBodyFile
			}
		}
		if sms != nil {
			if s, ok := sms[loc]; ok {
				spec.SMSTextFile = s.SMSTextFile
			}
		}
		out[loc] = spec
	}
	return out
}
