package auth

import (
	"github.com/tech/sendico/pkg/auth/internal/casbin"
	"github.com/tech/sendico/pkg/auth/internal/native"
	"github.com/tech/sendico/pkg/db/policy"
	"github.com/tech/sendico/pkg/db/role"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/mlogger"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.uber.org/zap"
)

func CreateAuth(
	logger mlogger.Logger,
	client *mongo.Client,
	db *mongo.Database,
	pdb policy.DB,
	rdb role.DB,
	config *Config,
) (Enforcer, Manager, error) {
	lg := logger.Named("auth")
	if config == nil || config.Driver == "" {
		lg.Warn("Permissions enforcer config is missing, defaulting to native enforcer")
		config = &Config{
			Driver: Native,
		}
	}
	lg.Debug("Creating enforcer...", zap.String("driver", string(config.Driver)))
	l := lg.Named(string(config.Driver))
	if config.Driver == Casbin {
		enforcer, err := casbin.NewEnforcer(l, client, config.Settings)
		if err != nil {
			lg.Warn("Failed to create enforcer", zap.Error(err))
			return nil, nil, err
		}
		manager, err := casbin.NewManager(l, pdb, rdb, enforcer, config.Settings)
		if err != nil {
			lg.Warn("Failed to create managment interface", zap.Error(err))
			return nil, nil, err
		}
		return enforcer, manager, nil
	}
	if config.Driver == Native {
		enforcer, err := native.NewEnforcer(l, db)
		if err != nil {
			lg.Warn("Failed to create enforcer", zap.Error(err))
			return nil, nil, err
		}
		manager, err := native.NewManager(l, pdb, rdb, enforcer)
		if err != nil {
			lg.Warn("Failed to create managment interface", zap.Error(err))
			return nil, nil, err
		}
		return enforcer, manager, nil
	}
	return nil, nil, merrors.InvalidArgument("Unknown enforcer type: "+string(config.Driver), "config.driver")
}
