package middleware

import (
	"net/http"
	"strings"

	"code.nonshy.com/nonshy/website/pkg/models"
	"code.nonshy.com/nonshy/website/pkg/templates"
	"code.nonshy.com/nonshy/website/pkg/utility"
)

// AgeGate: part of LoginRequired that verifies the user has a birthdate on file.
func AgeGate(user *models.User, w http.ResponseWriter, r *http.Request) (handled bool) {
	// Whitelisted endpoints where we won't redirect them away
	var whitelistedPaths = []string{
		"/me",
		"/settings",
		"/messages",
		"/friends",
		"/u/",
		"/photo/upload",
		"/photo/certification",
		"/photo/private",
		"/photo/view",
		"/photo/u/",
		"/comments",
		"/users/blocked",
		"/users/block",
		"/account/delete",
		"/v1/", // API endpoints like the Like buttons
	}
	for _, path := range whitelistedPaths {
		if strings.HasPrefix(r.URL.Path, path) {
			return
		}
	}

	// User has no age set? Redirect them to the age gate prompt.
	if user.Birthdate.IsZero() || utility.Age(user.Birthdate) < 18 {
		templates.Redirect(w, "/settings/age-gate")
		return true
	}

	return
}
