package main

import (
	"context"
	"fmt"
	"io"
	"strings"

	"github.com/fastly/compute-sdk-go/fsthttp"
)

// BackendName is the name of our service backend.
const BackendName = "origin_0"

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Get the response from the origin
		resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

    	// Split the URL by /
		url_parts := strings.Split(r.URL.Path[1:], "/")
		// Keep running track of the path
		running_path := "/"
		delimiter := ""
		// Loop through all of the URL parts
		for _, url_part := range url_parts {
			// Add the current part to the running path
			running_path += delimiter + url_part
			// Add the partial path to the surrogate keys array
			resp.Header.Add("Surrogate-Key", running_path)
			delimiter = "/"
		}

		// Log the surrogate key
		fmt.Println("Surrogate Keys:", resp.Header["Surrogate-Key"])

		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		_, err = io.Copy(w, resp.Body)
		if err != nil {
			w.WriteHeader(fsthttp.StatusInternalServerError)
			fmt.Fprintf(w, "failed to copy response body: %s", err)
		}
	})
}