package peer

import (
	"strconv"

	"cloud.o-forge.io/core/oc-lib/dbs"
	"cloud.o-forge.io/core/oc-lib/logs"
	"cloud.o-forge.io/core/oc-lib/models/utils"
	"cloud.o-forge.io/core/oc-lib/tools"
)

type peerMongoAccessor struct {
	utils.AbstractAccessor[*Peer] // AbstractAccessor contains the basic fields of an accessor (model, caller)
	OverrideAuth                  bool
}

// New creates a new instance of the peerMongoAccessor
func NewShallowAccessor() *peerMongoAccessor {
	return &peerMongoAccessor{
		OverrideAuth: true,
		AbstractAccessor: utils.AbstractAccessor[*Peer]{
			Logger: logs.CreateLogger(tools.PEER.String()), // Create a logger with the data type
			Type:   tools.PEER,
			New:    func() *Peer { return &Peer{} },
		},
	}
}

func NewAccessor(request *tools.APIRequest) *peerMongoAccessor {
	return &peerMongoAccessor{
		OverrideAuth: false,
		AbstractAccessor: utils.AbstractAccessor[*Peer]{
			Logger:  logs.CreateLogger(tools.PEER.String()), // Create a logger with the data type
			Request: request,
			Type:    tools.PEER,
			New:     func() *Peer { return &Peer{} },
		},
	}
}

func (wfa *peerMongoAccessor) ShouldVerifyAuth() bool {
	return !wfa.OverrideAuth
}

/*
TODO : organization_ID est un peer_ID duquel on se revendique faire parti.
Ca implique une clé d'organisation + une demande d'intégration.

Slave-Master IOT
*/
func (dca *peerMongoAccessor) StoreOne(data utils.DBObject) (utils.DBObject, int, error) {
	pp, _ := utils.GetMySelf(NewAccessor(&tools.APIRequest{Admin: true}))
	if data != nil {
		d := data.(*Peer)
		if pp != nil && d.OrganizationID != "" && d.OrganizationID == pp.(*Peer).OrganizationID {
			d.Relation = PARTNER // defaulting on partner if same organization.
		}
	}
	return utils.GenericStoreOne(data, dca)
}

/*
* Nothing special here, just the basic CRUD operations
 */
func (a *peerMongoAccessor) GetObjectFilters(search string) *dbs.Filters {
	if i, err := strconv.Atoi(search); err == nil {
		m := map[string][]dbs.Filter{ // search by name if no filters are provided
			"relation": {{Operator: dbs.EQUAL.String(), Value: i}},
		}
		if i == PARTNER.EnumIndex() {
			m["verify"] = []dbs.Filter{{Operator: dbs.EQUAL.String(), Value: false}}
		}
		return &dbs.Filters{
			Or: m,
		}
	} else {
		if search == "*" {
			search = ""
		}
		return &dbs.Filters{
			Or: map[string][]dbs.Filter{ // search by name if no filters are provided
				"abstractobject.name": {{Operator: dbs.LIKE.String(), Value: search}},
				"url":                 {{Operator: dbs.LIKE.String(), Value: search}},
				"peer_id":             {{Operator: dbs.LIKE.String(), Value: search}},
			},
		}
	}
}
