package keystore

import (
	"time"

	"code.justin.tv/sse/malachai/pkg/internal/discovery"
	"code.justin.tv/sse/malachai/pkg/jwtvalidation"
)

// PurgeExpiredKeys iterates through the in memory cache and purges expired
// keys
func (s *Store) PurgeExpiredKeys() error {
	var err error
	s.store.Range(func(key, value interface{}) bool {
		pubkey, ok := value.(*discovery.PublicKey)
		if !ok {
			s.store.Delete(key)
			return true
		}

		if pubkey.ExpireAt.Before(time.Now()) {
			signingEntity, ok := key.(jwtvalidation.SigningEntity)
			if !ok {
				s.store.Delete(key)
				return true
			}

			err = s.InvalidateRSAPublicKey(&signingEntity)
			if err != nil {
				return false
			}
		}
		return true
	})
	return err
}
