package main

import (
	"context"
	"fmt"
	"io"
  "regexp"
  "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) {

    if r.Method == "POST" {
      // Parse request body.
      reqBody, err := io.ReadAll(r.Body)
      if err != nil {
        w.WriteHeader(fsthttp.StatusInternalServerError)
        fmt.Fprintln(w, err.Error())
        return
      }
      // Extract the query
        re := regexp.MustCompile(`"query":\s"([^"]+)"`)
        match := re.FindStringSubmatch(string(reqBody))
        query := strings.ReplaceAll(match[1], "\\n", "")
        r.URL.Path = "/v1/graphql"
        // Append GraphQL query as a query string.
        qs := r.URL.Query()
        qs.Set("query", query)
        r.URL.RawQuery = qs.Encode()
        // Change request method to GET, so that response will get cached.
        r.Method = "GET"
    }
		resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}