package casbin

import (
	"github.com/casbin/casbin/v2"
	mongodbadapter "github.com/casbin/mongodb-adapter/v4"
	cc "github.com/tech/sendico/pkg/auth/internal/casbin/config"
	"github.com/tech/sendico/pkg/mlogger"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.uber.org/zap"
)

func createAdapter(logger mlogger.Logger, config *cc.Config, client *mongo.Client) (*casbin.Enforcer, error) {
	dbc, err := cc.PrepareConfig(logger, config)
	if err != nil {
		logger.Warn("Failed to prepare database configuration", zap.Error(err))
		return nil, err
	}

	adapter, err := mongodbadapter.NewAdapterByDB(client, dbc.Adapter)
	if err != nil {
		logger.Warn("Failed to create DB adapter", zap.Error(err))
		return nil, err
	}

	e, err := casbin.NewEnforcer(dbc.ModelPath, adapter, NewCasbinLogger(logger))
	if err != nil {
		logger.Warn("Failed to create permissions enforcer", zap.Error(err))
		return nil, err
	}
	e.EnableAutoSave(true)

	// No need to manually load policy. Casbin does it for us
	return e, nil
}
