package manifest

import (
	"net/http"

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

type Manifest struct {
	Name            string `json:"name"`
	ShortName       string `json:"short_name"`
	Description     string `json:"description"`
	Icons           []Icon `json:"icons"`
	StartURL        string `json:"start_url"`
	Display         string `json:"display"`
	BackgroundColor string `json:"background_color"`
	ThemeColor      string `json:"theme_color"`
	Lang            string `json:"lang"`
	Author          string `json:"author"`
	OgHost          string `json:"ogHost"`
	Orientation     string `json:"orientation"`
}

type Icon struct {
	Src   string `json:"src"`
	Sizes string `json:"sizes"`
	Type  string `json:"type"`
}

func ServeManifst(app *pocketbase.PocketBase, se *core.ServeEvent) *router.Route[*core.RequestEvent] {
	return se.Router.GET("/api/manifest.json", func(e *core.RequestEvent) error {
		manifest, err := GetSettings(app)
		if err != nil {
			return err
		}
		e.Response.Header().Add("content-type", "application/json")
		return e.String(http.StatusOK, manifest)
	})
}

func GetSettings(app *pocketbase.PocketBase) (string, error) {
	record, err := app.FindFirstRecordByFilter("settings", "key='manifest'", nil)
	if err != nil {
		return "", err
	}

	return record.GetString("value"), nil
}
