package organizationimp

import (
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"github.com/tech/sendico/server/interface/api/sresponse"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.uber.org/zap"
)

func (a *OrganizationAPI) invitation(r *http.Request, account *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	invitationRef, err := mutil.GetInvitationRef(r)
	if err != nil {
		a.logger.Warn("Failed to parse organization id", zap.Error(err), zap.String("invitation_ref", mutil.GetOrganizationID(r)))
		return response.Auto(a.logger, a.Name(), merrors.InvalidArgument("bad invitation reference"))
	}
	ctx := r.Context()

	var invitation model.Invitation
	if err := a.idb.Get(ctx, *account.GetID(), invitationRef, &invitation); err != nil {
		a.logger.Warn("Failed to fetch invitation", zap.Error(err), mzap.ObjRef("invitation_ref", invitationRef))
		return response.Auto(a.logger, a.Name(), err)
	}

	var org model.Organization
	if err := a.db.Get(ctx, *account.GetID(), invitation.OrganizationRef, &org); err != nil {
		a.logger.Error("Error fetching organization", zap.Error(err),
			mzap.StorableRef(&invitation), mzap.ObjRef("organization_ref", invitation.OrganizationRef))
		return response.Auto(a.logger, a.Name(), err)
	}

	return sresponse.OrganizationPublic(a.logger, &org.OrganizationBase)
}
