package gtm

import (
	"bytes"
	"encoding/json"
	"net/http"
	"text/template"

	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/core"
	"github.com/pocketbase/pocketbase/tools/router"
)

func ServeTagMangerJS(app *pocketbase.PocketBase, se *core.ServeEvent) *router.Route[*core.RequestEvent] {
	return se.Router.GET("/api/gtm/script.js", func(e *core.RequestEvent) error {

		settings, err := GetSettings(app)
		if err != nil {
			return err
		}

		file, err := JS.ReadFile("gtm.js")
		if err != nil {
			return err
		}
		templ, err := template.New("test").Parse(string(file))

		buf := bytes.Buffer{}
		templ.Execute(&buf, map[string]interface{}{
			"GtagID": settings.GtagID,
		})
		if err != nil {
			return err
		}

		e.Response.Header().Set("Content-Type", "application/javascript")
		return e.String(http.StatusOK, buf.String())
	})
}

type GTagSettings struct {
	GtagID string `json:"gtagID"`
}

func GetSettings(app *pocketbase.PocketBase) (*GTagSettings, error) {
	record, err := app.FindFirstRecordByFilter("settings", "key='gtagID'", nil)

	settings := GTagSettings{}
	json.Unmarshal([]byte(record.GetString("value")), &settings)

	if err != nil {
		return nil, err
	}

	return &settings, nil
}
