// https://developer.fastly.com/solutions/examples/overriding-ttls-path-prefix
package main

import (
	"context"
	"fmt"
	"io"
	"strconv"

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

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

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

// DefaultTTL is the default cache object TTL in seconds.
const DefaultTTL = 60

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Open dictionary containing TTL information.
		d, err := edgedict.Open(DictName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusInternalServerError)
			fmt.Fprintln(w, err)
			return
		}

		// Set default cache object TTL for all requests.
		r.CacheOptions.TTL = DefaultTTL

		// Override cache object TTL based on edge dictionary value.
		if v, _ := d.Get(r.URL.Path); v != "" {
			if i, err := strconv.ParseUint(v, 10, 32); err == nil {
				r.CacheOptions.TTL = uint32(i)
			}
		}

		fmt.Println("TTL:", r.CacheOptions.TTL)

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

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