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
		}

    // Check if the origin is sending back "immutable" in the Cache-Control header
    if (!strings.Contains(resp.Header.Get("cache-control"), "immutable")) {
      // Immutable not found, so add the "all" surrogate key
      resp.Header.Add("Surrogate-Key", "all")
    }
    // Add the pathname as a surrogate key as well
    resp.Header.Add("Surrogate-Key", r.URL.Path)

    // 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)
		}
	})
}