package web

import (
	"encoding/json"

	"ymhut-box/server/unified-management/internal/config"
)

const brandingSettingKey = "branding"

func (r *router) effectiveBranding() config.BrandingConfig {
	branding := config.NormalizeBranding(config.BrandingConfig{}, r.cfg.Branding)
	if r.store == nil {
		return branding
	}
	raw, err := r.store.GetSetting(brandingSettingKey)
	if err != nil || raw == "" {
		return branding
	}
	var stored config.BrandingConfig
	if json.Unmarshal([]byte(raw), &stored) != nil {
		return branding
	}
	return config.NormalizeBranding(branding, stored)
}

func (r *router) saveBranding(branding config.BrandingConfig) error {
	branding = config.NormalizeBranding(r.cfg.Branding, branding)
	next := *r.cfg
	next.Branding = branding
	next.Mail.DeveloperAddress = firstNonEmpty(next.Mail.DeveloperAddress, branding.FeedbackEmail)
	if err := config.Save(&next); err != nil {
		return err
	}
	r.cfg.Branding = next.Branding
	r.cfg.Mail = next.Mail
	data, err := json.Marshal(r.cfg.Branding)
	if err != nil {
		return err
	}
	return r.store.UpsertSetting(brandingSettingKey, string(data))
}
