package main

import (
	"bytes"
	"context"
	"encoding/base64"
	"fmt"
	"io"

	"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 this is a POST request
		if r.Method == fsthttp.MethodPost {
			// Get the body of the request
			body, err := io.ReadAll(r.Body)
			if err != nil {
				w.WriteHeader(fsthttp.StatusInternalServerError)
				fmt.Fprintln(w, err.Error())
				return
			}

			// Encode the body as base64
			encodedBody := make([]byte, base64.StdEncoding.EncodedLen(len(body)))
			base64.StdEncoding.Encode(encodedBody, body)

			// Log the base64 encoded body
			fmt.Println(string(encodedBody))

			// Update the request with the base64 encoded body
			r.Body = io.NopCloser(bytes.NewReader(encodedBody))
		}

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

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