package auth

import (
	"context"
	"github.com/dgrijalva/jwt-go"
	"go.uber.org/dig"
	"yx-dataset-server/app/errors"
	"yx-dataset-server/library/auth/store/redis"
	"yx-dataset-server/library/utils"
)

func InitAuth(ctx context.Context, container *dig.Container) error {
	var opts []Option
	opts = append(opts, SetExpired(utils.GetConfig("jwt.expired").Int()))
	opts = append(opts, SetSigningKey([]byte(utils.GetConfig("jwt.signing_key").String())))
	opts = append(opts, SetKeyfunc(func(t *jwt.Token) (interface{}, error) {
		if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.ErrInvalidToken
		}
		return []byte(utils.GetConfig("jwt.signing_key").String()), nil
	}))

	switch utils.GetConfig("jwt.signing_method").String() {
	case "HS256":
		opts = append(opts, SetSigningMethod(jwt.SigningMethodHS256))
	case "HS384":
		opts = append(opts, SetSigningMethod(jwt.SigningMethodHS384))
	case "HS512":
		opts = append(opts, SetSigningMethod(jwt.SigningMethodHS512))
	}
	store := redis.NewStore(&redis.Config{
		Addr:      utils.GetConfig("redis.addr").String(),
		Password:  utils.GetConfig("redis.password").String(),
		DB:        utils.GetConfig("jwt.redis_db").Int(),
		KeyPrefix: utils.GetConfig("redis.redis_prefix").String(),
	})
	return container.Provide(func() Auther { return New(store, opts...) })
}
