package booking

import (
	"time"

	"cloud.o-forge.io/core/oc-lib/dbs"
	"cloud.o-forge.io/core/oc-lib/models/utils"
	"cloud.o-forge.io/core/oc-lib/models/workflow_execution"
	"cloud.o-forge.io/core/oc-lib/tools"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

/*
* Booking is a struct that represents a booking
 */
type Booking struct {
	workflow_execution.WorkflowExecution        // WorkflowExecution contains the workflow execution data
	ComputeResourceID                    string `json:"compute_resource_id,omitempty" bson:"compute_resource_id,omitempty" validate:"required"` // ComputeResourceID is the ID of the compute resource specified in the booking
}

// CheckBooking checks if a booking is possible on a specific compute resource
func (wfa *Booking) CheckBooking(id string, start time.Time, end *time.Time) (bool, error) {
	// check if
	if end == nil {
		// if no end... then Book like a savage
		return true, nil
	}
	e := *end
	accessor := New(tools.BOOKING, "", nil, nil)
	res, code, err := accessor.Search(&dbs.Filters{
		And: map[string][]dbs.Filter{ // check if there is a booking on the same compute resource by filtering on the compute_resource_id, the state and the execution date
			"compute_resource_id":     {{Operator: dbs.EQUAL.String(), Value: id}},
			"workflowexecution.state": {{Operator: dbs.EQUAL.String(), Value: workflow_execution.SCHEDULED.EnumIndex()}},
			"workflowexecution.execution_date": {
				{Operator: dbs.LTE.String(), Value: primitive.NewDateTimeFromTime(e)},
				{Operator: dbs.GTE.String(), Value: primitive.NewDateTimeFromTime(start)},
			},
		},
	}, "")
	if code != 200 {
		return false, err
	}
	return len(res) == 0, nil
}

// tool to convert the argo status to a state
func (wfa *Booking) ArgoStatusToState(status string) *Booking {
	wfa.WorkflowExecution.ArgoStatusToState(status)
	return wfa
}

func (d *Booking) GetName() string {
	return d.UUID + "_" + d.ExecDate.String()
}

func (d *Booking) GetAccessor(peerID string, groups []string, caller *tools.HTTPCaller) utils.Accessor {
	return New(tools.BOOKING, peerID, groups, caller) // Create a new instance of the accessor
}
