package permissionsimp

import (
	"context"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"github.com/tech/sendico/server/interface/api/sresponse"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.uber.org/zap"
)

func (a *PermissionsAPI) permissions(ctx context.Context, organizationRef bson.ObjectID, roles []model.Role, permissions []model.Permission, accessToken *sresponse.TokenData) http.HandlerFunc {
	roleDescs, err := a.rdb.List(ctx, organizationRef, nil)
	if err != nil {
		a.logger.Warn("Failed to fetch organization roles", zap.Error(err), mzap.ObjRef("organization_ref", organizationRef))
		return response.Internal(a.logger, a.Name(), err)
	}
	permDescs, err := a.pdb.All(ctx, organizationRef)
	if err != nil {
		a.logger.Warn("Failed to fetch organization permissions", zap.Error(err), mzap.ObjRef("organization_ref", organizationRef))
		return response.Internal(a.logger, a.Name(), err)
	}
	policies, err := a.getRolePolicies(ctx, roleDescs)
	if err != nil {
		a.logger.Warn("Failed to fetch roles policies", zap.Error(err))
		return response.Auto(a.logger, a.Name(), err)
	}

	return sresponse.Permisssions(a.logger, roleDescs, permDescs, roles, policies, permissions, accessToken)
}
