package logoimp

import (
	_ "embed"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	"github.com/tech/sendico/server/assets"
	"github.com/tech/sendico/server/internal/mutil/imagewriter"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.uber.org/zap"
)

func (a *LogoAPI) getLogo(r *http.Request) http.HandlerFunc {
	accountRef, err := mutil.GetAccountRef(r)
	if err != nil {
		a.logger.Warn("Invalid account reference", zap.Error(err))
		return response.BadReference(a.logger, a.Name(), mutil.AccountRefName(), mutil.GetAccountID(r), err)
	}
	// new context for execution
	var account model.Account
	if err := a.adb.Get(r.Context(), accountRef, &account); err != nil {
		a.logger.Warn("Failed to fetch account data", zap.Error(err))
		return response.NotFound(a.logger, mservice.Accounts, err.Error())
	}

	res := func(w http.ResponseWriter, r *http.Request) {
		// TODO: delayed response due to context expiration after writing reposnse :(
		if err = imagewriter.WriteImage(w, &assets.MailLogo, "image/png"); err != nil {
			a.logger.Error("Failed to send logo", zap.Error(err))
		}

		// ma.Identify(acc.Email)
		// ampli.Instance.EmailOpened(acc.Email,
		// 	ampli.EmailOpened.Builder().EmailType(mutil.GetParam(r, "email_type")).Build())
	}
	return res
}
