package oidc

import (
	"errors"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

var errInvalidCacheControlHeader = errors.New("expected a Cache-Control header of the format max-age=3600")
var cacheControlRegex = regexp.MustCompile(`max-age=(\d+)`)

func parseCacheControlMaxAge(r *http.Response) (time.Duration, error) {
	if m := cacheControlRegex.FindStringSubmatch(r.Header.Get("Cache-Control")); len(m) >= 2 {
		asInt, err := strconv.Atoi(m[1])
		if err != nil {
			return 0, err
		}
		return time.Duration(asInt) * time.Second, nil
	}
	return 0, errInvalidCacheControlHeader
}
