package workflow_execution

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 workflowExecutionMongoAccessor struct {
	utils.AbstractAccessor
}

func New(t tools.DataType, peerID string, groups []string, caller *tools.HTTPCaller) *workflowExecutionMongoAccessor {
	return &workflowExecutionMongoAccessor{
		utils.AbstractAccessor{
			Logger: logs.CreateLogger(t.String()), // Create a logger with the data type
			Caller: caller,
			PeerID: peerID,
			Groups: groups, // Set the caller
			Type:   t,
		},
	}
}

func (wfa *workflowExecutionMongoAccessor) DeleteOne(id string) (utils.DBObject, int, error) {
	return utils.GenericDeleteOne(id, wfa)
}

func (wfa *workflowExecutionMongoAccessor) UpdateOne(set utils.DBObject, id string) (utils.DBObject, int, error) {
	return utils.GenericUpdateOne(set, id, wfa, &WorkflowExecution{})
}

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

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

func (a *workflowExecutionMongoAccessor) LoadOne(id string) (utils.DBObject, int, error) {
	return utils.GenericLoadOne[*WorkflowExecution](id, func(d utils.DBObject) (utils.DBObject, int, error) {
		if d.(*WorkflowExecution).State == SCHEDULED && time.Now().UTC().After(*d.(*WorkflowExecution).ExecDate) {
			d.(*WorkflowExecution).State = FORGOTTEN
			utils.GenericRawUpdateOne(d, id, a)
		}
		return d, 200, nil
	}, a)
}

func (a *workflowExecutionMongoAccessor) LoadAll() ([]utils.ShallowDBObject, int, error) {
	return utils.GenericLoadAll[*WorkflowExecution](a.getExec(), a)
}

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

func (a *workflowExecutionMongoAccessor) getExec() func(utils.DBObject) utils.ShallowDBObject {
	return func(d utils.DBObject) utils.ShallowDBObject {
		if d.(*WorkflowExecution).State == SCHEDULED && time.Now().UTC().After(*d.(*WorkflowExecution).ExecDate) {
			d.(*WorkflowExecution).State = FORGOTTEN
			utils.GenericRawUpdateOne(d, d.GetID(), a)
		}
		return d
	}
}
