package accountapiimp

import (
	"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 *AccountAPI) getEmployees(r *http.Request, account *model.Account, token *sresponse.TokenData) http.HandlerFunc {
	orgRef, err := a.oph.GetRef(r)
	if err != nil {
		a.logger.Warn("Failed to fetch organizaiton reference", zap.Error(err), zap.String(a.oph.Name(), a.oph.GetID(r)))
		return response.BadReference(a.logger, a.Name(), a.oph.Name(), a.oph.GetID(r), err)
	}
	ctx := r.Context()
	res, err := a.enf.Enforce(ctx, a.accountsPermissionRef, account.ID, orgRef, bson.NilObjectID, model.ActionRead)
	if err != nil {
		a.logger.Warn("Failed to check accounts access permissions", zap.Error(err), mzap.ObjRef("organization_ref", orgRef), mzap.StorableRef(account))
		return response.Auto(a.logger, a.Name(), err)
	}
	if !res {
		a.logger.Debug("Access denied when reading organization employees", mzap.StorableRef(account))
		return response.AccessDenied(a.logger, a.Name(), "orgnizations employees read permission denied")
	}
	var org model.Organization
	if err := a.odb.Get(ctx, *account.GetID(), orgRef, &org); err != nil {
		a.logger.Warn("Failed to fetch organization", zap.Error(err), mzap.ObjRef("organization_ref", orgRef), mzap.StorableRef(account))
		return response.Auto(a.logger, a.Name(), err)
	}

	emps, err := a.db.GetAccountsByRefs(ctx, orgRef, org.Members)
	if err != nil {
		a.logger.Warn("Failed to fetch organization emplpyees", zap.Error(err), mzap.ObjRef("organization_ref", orgRef), mzap.StorableRef(account))
		return response.Auto(a.logger, a.Name(), err)
	}

	return sresponse.Accounts(a.logger, emps, orgRef, token)
}
