package routes

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

	"bitbucket.org/imediabrands/oos-service/middlewares"
)

const prodRobotsTxt = `User-agent: *
Allow: /
Disallow: /search?term=

User-agent: GPTBot
Allow: /

User-agent: ChatGPT-User
Allow: /

User-agent: Google-Extended
Allow: /

User-agent: ClaudeBot
Allow: /

User-agent: anthropic-ai
Allow: /

User-agent: PerplexityBot
Allow: /

Sitemap: %s/sitemap.xml
`

func RobotsTxtRouteHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())

		disallow := false
		if config != nil && config.GetString("disallowRobots") == "true" {
			disallow = true
		}
		// Keep UAT / staging / development hosts out of organic crawl indexes.
		if !isSitemapIndexableHost(req) {
			disallow = true
		}

		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		if disallow {
			fmt.Fprint(w, "User-agent: *\nDisallow: /\n")
			return
		}

		base := strings.TrimRight(requestPublicBaseURL(req), "/")
		fmt.Fprintf(w, prodRobotsTxt, base)
	})
}
