package setup

import (
	"time"

	"forge.cadoles.com/cadoles/bouncer/internal/config"
	"forge.cadoles.com/cadoles/bouncer/internal/proxy/director"
	"forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn"
	"forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn/oidc"
	"forge.cadoles.com/cadoles/bouncer/internal/schema"
	"forge.cadoles.com/cadoles/bouncer/internal/session"
	"forge.cadoles.com/cadoles/bouncer/internal/session/adapter/redis"
	"github.com/pkg/errors"
)

func init() {
	extended, err := schema.Extend(authn.RawLayerOptionsSchema, oidc.RawLayerOptionsSchema)
	if err != nil {
		panic(errors.Wrap(err, "could not extend authn base layer options schema"))
	}

	RegisterLayer(oidc.LayerType, setupAuthnOIDCLayer, extended)
}

func setupAuthnOIDCLayer(conf *config.Config) (director.Layer, error) {
	rdb := NewSharedClient(conf.Redis)
	adapter := redis.NewStoreAdapter(rdb)
	store := session.NewStore(adapter)

	transport := conf.Layers.Authn.OIDC.HTTPClient.AsTransport()

	return oidc.NewLayer(
		store,
		oidc.WithHTTPTransport(transport),
		oidc.WithHTTPClientTimeout(time.Duration(*conf.Layers.Authn.OIDC.HTTPClient.Timeout)),
		oidc.WithAuthnOptions(
			authn.WithTemplateDir(string(conf.Layers.Authn.TemplateDir)),
			authn.WithDebug(bool(conf.Layers.Authn.Debug)),
		),
	), nil
}