package auth

import (
	"context"
	"errors"

	"github.com/tech/sendico/pkg/db/repository"
	"github.com/tech/sendico/pkg/db/repository/builder"
	"github.com/tech/sendico/pkg/db/template"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.uber.org/zap"
)

func enforceObject[T model.PermissionBoundStorable](ctx context.Context, db *template.DBImp[T], enforcer Enforcer, action model.Action, accountRef bson.ObjectID, query builder.Query) error {
	l, err := db.ListPermissionBound(ctx, query)
	if err != nil {
		db.Logger.Warn("Error occured while checking access rights", zap.Error(err),
			mzap.AccRef(accountRef), zap.String("action", string(action)))
		return err
	}
	if len(l) == 0 {
		db.Logger.Debug("Access denied", mzap.AccRef(accountRef), zap.String("action", string(action)))
		return merrors.AccessDenied(db.Repository.Collection(), string(action), bson.NilObjectID)
	}
	for _, item := range l {
		db.Logger.Debug("Object found", mzap.ObjRef("object_ref", *item.GetID()),
			mzap.ObjRef("organization_ref", item.GetOrganizationRef()),
			mzap.ObjRef("permission_ref", item.GetPermissionRef()),
			zap.String("collection", item.Collection()))
	}
	res, err := enforcer.EnforceBatch(ctx, l, accountRef, action)
	if err != nil {
		db.Logger.Warn("Failed to enforce permission", zap.Error(err),
			mzap.AccRef(accountRef), zap.String("action", string(action)))
	}
	for objectRef, hasPermission := range res {
		if !hasPermission {
			db.Logger.Info("Permission denied for object during reordering", mzap.AccRef(accountRef),
				mzap.ObjRef("object_ref", objectRef), zap.String("action", string(model.ActionUpdate)))
			return merrors.AccessDenied(db.Repository.Collection(), string(action), objectRef)
		}
	}
	return nil
}

func enforceObjectByRef[T model.PermissionBoundStorable](ctx context.Context, db *template.DBImp[T], enforcer Enforcer, action model.Action, accountRef, objectRef bson.ObjectID) error {
	err := enforceObject(ctx, db, enforcer, action, accountRef, repository.IDFilter(objectRef))
	if err != nil {
		if errors.Is(err, merrors.ErrAccessDenied) {
			db.Logger.Debug("Access denied", mzap.AccRef(accountRef), mzap.ObjRef("object_ref", objectRef), zap.String("action", string(action)))
			return merrors.AccessDenied(db.Repository.Collection(), string(action), objectRef)
		} else {
			db.Logger.Warn("Error occurred while checking permissions", zap.Error(err),
				mzap.AccRef(accountRef), mzap.ObjRef("object_ref", objectRef), zap.String("action", string(action)))
		}
	}
	return err
}
