// https://developer.fastly.com/solutions/examples/compute-intersection-of-two-lists

package main

import (
	"context"
	"fmt"
	"io"
  "regexp"
  "strings"

	"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) {
		// This requires your service to be configured with a backend
		// named "origin_0" and pointing to "https://http-me.glitch.me".

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

    // Extract pemission values from cookie header.
    cookie := r.Header.Get("cookie")
    re := regexp.MustCompile(`permission=:(.+:.+:.+):;`)
    permission := re.FindStringSubmatch(cookie)
    PermValues := strings.Split(permission[1], ":")

    // Extract require-group values from response header.
    q := resp.Header.Get("require-group")
    re = regexp.MustCompile(`:(.+):`)
    qs := re.FindStringSubmatch(q)
    QValues := strings.Split(qs[1], ":")

    // Check for intersecting list.
    result := CheckIntersection(PermValues, QValues)
    fmt.Println(result)

    // If no intersection is found, return a 403 response.
    if result == "No intersection found" {
      resp := &fsthttp.Response{
        StatusCode: fsthttp.StatusForbidden,
        Body: io.NopCloser(strings.NewReader("")),
      }
      w.Header().Reset(resp.Header)
	    w.WriteHeader(resp.StatusCode)
	    io.Copy(w, resp.Body)
      return
    }

		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}

// CheckIntersection() function checks for the common values in two slices
// and returns a string containing those values.
func CheckIntersection(first []string, second []string) string {
  var result string
  for _, f := range first {
    for _, s := range second {
      if s == f {
        result += s + " "
      }
    }
  }
  if len(result) > 0 {
    return "Intersection: " + result
  }else{
    return "No intersection found"
  }
}