// https://developer.fastly.com/solutions/examples/replace-origin-errors-with--safe--responses
package main

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

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

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

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Send the request to the named backend.
		resp, err := r.Send(ctx, Backend)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err)
			return
		}

		switch resp.StatusCode {
		case fsthttp.StatusUnavailableForLegalReasons:
			h := fsthttp.NewHeader()
			h.Add("Content-Type", "text/html; charset=utf-8")

			// Generate a synthetic response.
			resp = &fsthttp.Response{
				Header:     h,
				StatusCode: resp.StatusCode,
				Body:       io.NopCloser(strings.NewReader(fmt.Sprintf(synth, resp.StatusCode))),
			}
		case fsthttp.StatusServiceUnavailable, fsthttp.StatusInternalServerError:
			// A request can't call .Send() twice.
			rc := r.Clone()

			// Modify the path to return a custom error page.
			rc.URL.Path = "/anything/some/error/page"

			// Track the original status code.
			originalStatus := resp.StatusCode

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

			// Reassign the original status code.
			// Otherwise the status would be a misleading "200 OK".
			resp.StatusCode = originalStatus
		}

		// Write response to client.
		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}

const synth = `
<!DOCTYPE html>
<html lang="en">
<head>
	<title>There was a problem</title>
	<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet" type="text/css">
	<style>
		body {{ display: inline-block; background: #7000f9 no-repeat; height: 100vh; margin: 0; color: white; }}
		h1 {{ margin: .8em 3rem; font: 4em Roboto; }}
		p {{ display: inline-block; margin: .2em 3rem; font: 2em Roboto; }}
	</style>
</head>
<body>
	<h1>%d APOLOGIES!</h1>
	<p>Something went wrong</p>
</body>
</html>
`