package purchase_resource

import (
	"time"

	"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 purchaseResourceMongoAccessor struct {
	utils.AbstractAccessor // AbstractAccessor contains the basic fields of an accessor (model, caller)
}

// New creates a new instance of the bookingMongoAccessor
func NewAccessor(request *tools.APIRequest) *purchaseResourceMongoAccessor {
	return &purchaseResourceMongoAccessor{
		AbstractAccessor: utils.AbstractAccessor{
			Logger:  logs.CreateLogger(tools.BUYING_STATUS.String()), // Create a logger with the data type
			Request: request,
			Type:    tools.BUYING_STATUS,
		},
	}
}

/*
* Nothing special here, just the basic CRUD operations
 */
func (a *purchaseResourceMongoAccessor) DeleteOne(id string) (utils.DBObject, int, error) {
	return utils.GenericDeleteOne(id, a)
}

func (a *purchaseResourceMongoAccessor) UpdateOne(set utils.DBObject, id string) (utils.DBObject, int, error) {
	return utils.GenericUpdateOne(set, id, a, &PurchaseResource{})
}

func (a *purchaseResourceMongoAccessor) StoreOne(data utils.DBObject) (utils.DBObject, int, error) {
	return utils.GenericStoreOne(data, a)
}

func (a *purchaseResourceMongoAccessor) CopyOne(data utils.DBObject) (utils.DBObject, int, error) {
	return utils.GenericStoreOne(data, a)
}

func (a *purchaseResourceMongoAccessor) LoadOne(id string) (utils.DBObject, int, error) {
	return utils.GenericLoadOne[*PurchaseResource](id, func(d utils.DBObject) (utils.DBObject, int, error) {
		if d.(*PurchaseResource).EndDate != nil && time.Now().UTC().After(*d.(*PurchaseResource).EndDate) {
			utils.GenericDeleteOne(id, a)
			return nil, 404, nil
		}
		return d, 200, nil
	}, a)
}

func (a *purchaseResourceMongoAccessor) LoadAll(isDraft bool) ([]utils.ShallowDBObject, int, error) {
	return utils.GenericLoadAll[*PurchaseResource](a.getExec(), isDraft, a)
}

func (a *purchaseResourceMongoAccessor) Search(filters *dbs.Filters, search string, isDraft bool) ([]utils.ShallowDBObject, int, error) {
	return utils.GenericSearch[*PurchaseResource](filters, search, (&PurchaseResource{}).GetObjectFilters(search), a.getExec(), isDraft, a)
}

func (a *purchaseResourceMongoAccessor) getExec() func(utils.DBObject) utils.ShallowDBObject {
	return func(d utils.DBObject) utils.ShallowDBObject {
		if d.(*PurchaseResource).EndDate != nil && time.Now().UTC().After(*d.(*PurchaseResource).EndDate) {
			utils.GenericDeleteOne(d.GetID(), a)
			return nil
		}
		return d
	}
}
