package purchase_resource

import (
	"time"

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

type PurchaseResource struct {
	utils.AbstractObject
	FromNano    string                 `json:"from_nano,omitempty" bson:"priced_item,omitempty"`
	DestPeerID  string                 `json:"dest_peer_id" bson:"dest_peer_id"`
	PricedItem  map[string]interface{} `json:"priced_item,omitempty" bson:"priced_item,omitempty" validate:"required"`
	ExecutionID string                 `json:"execution_id,omitempty" bson:"execution_id,omitempty" validate:"required"` // ExecutionsID is the ID of the executions

	ExecutionsID string     `json:"executions_id,omitempty" bson:"executions_id,omitempty" validate:"required"` // ExecutionsID is the ID of the executions
	EndDate      *time.Time `json:"end_buying_date,omitempty" bson:"end_buying_date,omitempty"`
	ResourceID   string     `json:"resource_id" bson:"resource_id" validate:"required"`
	InstanceID   string     `json:"instance_id,omitempty" bson:"instance_id,omitempty" validate:"required"` // could be a Compute or a Storage

	ResourceType tools.DataType `json:"resource_type" bson:"resource_type" validate:"required"`

	// Authorization: identifies who created this draft and the Check session it belongs to.
	SchedulerPeerID string `json:"scheduler_peer_id,omitempty" bson:"scheduler_peer_id,omitempty"`
}

func (ri *PurchaseResource) Extend(typ ...string) map[string][]tools.DataType {
	ext := ri.AbstractObject.Extend(typ...)
	for _, t := range typ {
		switch t {
		case "dest_peer", "scheduler_peer":
			if _, ok := ext[t]; !ok {
				ext[t] = []tools.DataType{}
			}
			ext[t] = append(ext[t], tools.PEER)
		case "execution":
			if _, ok := ext[t]; !ok {
				ext[t] = []tools.DataType{}
			}
			ext[t] = append(ext[t], tools.WORKFLOW_EXECUTION)
		case "resource":
			if _, ok := ext[t]; !ok {
				ext[t] = []tools.DataType{}
			}
			ext[t] = append(ext[t], tools.WORKFLOW_RESOURCE)
			ext[t] = append(ext[t], tools.DATA_RESOURCE)
			ext[t] = append(ext[t], tools.COMPUTE_RESOURCE)
			ext[t] = append(ext[t], tools.STORAGE_RESOURCE)
			ext[t] = append(ext[t], tools.PROCESSING_RESOURCE)
			ext[t] = append(ext[t], tools.SERVICE_RESOURCE)
		}
	}
	return ext
}
func (d *PurchaseResource) GetAccessor(request *tools.APIRequest) utils.Accessor {
	return NewAccessor(request) // Create a new instance of the accessor
}

func (r *PurchaseResource) CanUpdate(set utils.DBObject) (bool, utils.DBObject) {
	return r.IsDraft, set // only draft buying can be updated
}

func (r *PurchaseResource) CanDelete() bool { // ENDBuyingDate is passed
	if r.EndDate != nil {
		return time.Now().UTC().After(*r.EndDate)
	}
	return false // only draft bookings can be deleted
}
