package seo

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

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

type Robots struct {
	Robots []string
}

func ServeRobotsTxt(app *pocketbase.PocketBase, se *core.ServeEvent) *router.Route[*core.RequestEvent] {
	return se.Router.GET("/robots.txt", func(e *core.RequestEvent) error {

		text, err := getRobots(app)
		if err != nil {
			return err
		}
		return e.String(http.StatusOK, text)
	})
}

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

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

	if err != nil {
		return "", err
	}

	baseUrl, err := getBaseUrl(app)
	if err != nil {
		return "", err
	}

	settings.Robots = append(settings.Robots, fmt.Sprintf("\n\nSitemap: %s%s", baseUrl, "feeds/index.xml"))

	return strings.Join(settings.Robots, "\n"), nil
}
