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.uber.org/zap"
)

func (a *AccountAPI) dzone(r *http.Request, account *model.Account, token *sresponse.TokenData) http.HandlerFunc {
	ctx := r.Context()
	orgs, err := a.odb.List(ctx, account.ID, nil)
	if err != nil {
		a.logger.Error("Failed to list owned organizations", zap.Error(err), mzap.StorableRef(account))
		return response.Auto(a.logger, a.Name(), err)
	}

	orgsPBS := make([]model.PermissionBoundStorable, len(orgs))
	for i, org := range orgs {
		orgsPBS[i] = &org
	}
	res, err := a.enf.EnforceBatch(ctx, orgsPBS, account.ID, model.ActionDelete)
	if err != nil {
		a.logger.Error("Failed to enforce permissions", zap.Error(err), mzap.StorableRef(account))
		return response.Auto(a.logger, a.Name(), err)
	}
	validOrgs := make([]model.Organization, 0, len(orgs))
	for _, org := range orgs {
		if res[org.ID] {
			validOrgs = append(validOrgs, org)
			a.logger.Debug("Organization can be deleted", mzap.StorableRef(&org), mzap.StorableRef(account))
		} else {
			a.logger.Debug("Organization does not have delete permission for account", mzap.StorableRef(&org), mzap.StorableRef(account))
		}
	}

	return sresponse.DZone(
		a.logger,
		&model.DZone{
			CanDeleteAccount: true,
			CanDeleteCascade: len(validOrgs) > 0,
			Organizations:    validOrgs,
		},
		token,
	)
}
