package main

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

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

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		ip := net.ParseIP(r.RemoteAddr)
		if ip == nil {
			w.WriteHeader(fsthttp.StatusInternalServerError)
			fmt.Fprintln(w, "unable to parse the client IP %q", r.RemoteAddr)
			return
		}

		geo, err := geo.Lookup(ip)
		if err != nil {
			w.WriteHeader(fsthttp.StatusInternalServerError)
			fmt.Fprintln(w, err)
			return
		}

		// Build the log data as a map
		log_data := map[string]string{
			"timestamp":               time.Now().UTC().Format("2006-01-02T15:04:05.999Z07:00"),
			"client_ip":               ip.String(),
			"geo_city":                geo.City,
			"geo_country_code":        geo.CountryCode,
			"request":                 r.Method,
			"host":                    r.URL.Host,
			"url":                     r.URL.Path,
			"request_referer":         r.Header.Get("referer"),
			"request_user_agent":      r.Header.Get("user-agent"),
			"request_accept_language": r.Header.Get("accept-language"),
			"request_accept_charset":  r.Header.Get("accept-charset"),
		}
		// Marshall the log data into JSON
		log_data_bytes, _ := json.Marshal(log_data)

		// Open the connection to the logging endpoint
		endpoint := rtlog.Open("my_endpoint_name")
		// Write the log line
		fmt.Fprintln(endpoint, string(log_data_bytes))

		resp, err := r.Send(ctx, "origin_0")
		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)
	})
}