package main

import (
	"context"
	"fmt"
	"io"
	"os"

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

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// This variable is not defined in Fiddle but you see the possible values here: https://developer.fastly.com/reference/compute/ecp-env/fastly-region/
		var FastlyRegion = os.Getenv("FASTLY_REGION")

		RegionsToOrigins := map[string]string{
			"AF-West":       "origin_0", /* European origin */
			"APAC":          "origin_1", /* Asian origin */
			"Asia":          "origin_1", /* Asian origin */
			"Asia-South":    "origin_1", /* Asian origin */
			"EU-Central":    "origin_0", /* European origin */
			"EU-East":       "origin_0", /* European origin */
			"EU-West":       "origin_0", /* European origin */
			"North-America": "origin_2", /* American origin */
			"SA-East":       "origin_2", /* American origin */
			"SA-North":      "origin_2", /* American origin */
			"SA-South":      "origin_2", /* American origin */
			"South-Africa":  "origin_0", /* European origin */
			"US-Central":    "origin_2", /* American origin */
			"US-East":       "origin_2", /* American origin */
			"US-West":       "origin_2", /* American origin */
		}

		// We do not have backend health support in the Golang SDK at time of writing so the backend selection is based on region alone
		BackendName, found := RegionsToOrigins[FastlyRegion]
		// Check if the region is in the map of regions to backends
		if !found {
			// The region was not found so default to the European origin
			BackendName = "origin_0"
		}

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