package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

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

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

type simpleQRCode struct {
	Content string
	Size    int
}

func (code *simpleQRCode) Generate() ([]byte, error) {
	qrCode, err := qrcode.Encode(code.Content, qrcode.Medium, code.Size)
	if err != nil {
		return nil, fmt.Errorf("could not generate a QR code: %v", err)
	}
	return qrCode, nil
}

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Check if this is a request for a QR code
		if r.Method == "GET" && r.URL.Path == "/qr.png" {
			url := r.URL.Query().Get("url")
			// Check if the URL as been included in the querystring
			if url != "" {
				// Generate the QR code at 512x512 pixels
				qrCode := simpleQRCode{Content: url, Size: 512}
				codeData, err := qrCode.Generate()
				if err != nil {
					w.WriteHeader(400)
					json.NewEncoder(w).Encode(
						fmt.Sprintf("Could not generate QR code. %v", err),
					)
					return
				}

				// Return the QR code image as the result
				w.Header().Set("Content-Type", "image/png")
				w.Write(codeData)
			}
		}

		// Let other requests pass to the origin
		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)
	})
}