package main

import (
	"context"
	"fmt"
	"net/netip"

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

const IPV4_MASK = 24
const IPV6_MASK = 48

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		ip, err := netip.ParseAddr(r.RemoteAddr)
		if err != nil {
			fmt.Printf("error parsing IP %v", err)
			w.WriteHeader(fsthttp.StatusInternalServerError)
			return
		}

		anonIP, err := anonymize(ip)
		if err != nil {
			fmt.Printf("error anonymizing IP %v", err)
			w.WriteHeader(fsthttp.StatusInternalServerError)
			return
		}

		fmt.Printf("IP %s anonymized to %s\n", ip.String(), anonIP)

		w.WriteHeader(fsthttp.StatusOK)
    fmt.Fprint(w, anonIP)
	})
}

func anonymize(ip netip.Addr) (string, error) {
	var mask int
	if ip.Is4() {
		mask = IPV4_MASK
	} else if ip.Is6() {
		mask = IPV6_MASK
	}
	p, err := ip.Prefix(mask)

	if err != nil {
		return "", err
	}

	return p.Addr().String(), nil
}