// https://developer.fastly.com/solutions/examples/redirect-old-urls-at-the-edge
package main

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

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

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

// DictName is the name of our edge dictionary.
const DictName = "redirects"

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		fmt.Println("Request:", r.URL.Path)

		// Open dictionary containing redirect information.
		d, err := edgedict.Open(DictName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusInternalServerError)
			fmt.Fprintln(w, err)
			return
		}

		// If request path has a redirect, then return a 308 redirect.
		if v, _ := d.Get(r.URL.Path); v != "" {
			h := fsthttp.NewHeader()
			h.Add("Location", v)
			fmt.Println("Location:", v)

			// Generate a synthetic response.
			resp := &fsthttp.Response{
				Header:     h,
				StatusCode: fsthttp.StatusPermanentRedirect,
				Body:       io.NopCloser(strings.NewReader("")),
			}

			// Write response to client.
			flush(resp, w)
			return
		}

		// Send the request to the named backend.
		resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err)
			return
		}

		// Write response to client.
		flush(resp, w)
	})
}

func flush(resp *fsthttp.Response, w fsthttp.ResponseWriter) {
	w.Header().Reset(resp.Header)
	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}