package booking

import (
	"errors"
	"time"

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

type BookingMongoAccessor struct {
	utils.AbstractAccessor[*Booking] // AbstractAccessor contains the basic fields of an accessor (model, caller)
}

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

/*
* Nothing special here, just the basic CRUD operations
 */
func (a *BookingMongoAccessor) UpdateOne(set map[string]interface{}, id string) (utils.DBObject, int, error) {
	if set["state"] == nil {
		return nil, 400, errors.New("state is required")
	}
	set = map[string]interface{}{
		"state": set["state"],
	}
	return utils.GenericUpdateOne(set, id, a)
}

func (a *BookingMongoAccessor) LoadOne(id string) (utils.DBObject, int, error) {
	return utils.GenericLoadOne(id, a.New(), func(d utils.DBObject) (utils.DBObject, int, error) {
		now := time.Now()
		now = now.Add(time.Second * -60)
		if d.(*Booking).State == enum.DRAFT && now.UTC().After(d.(*Booking).ExpectedStartDate) {
			// Direct raw delete to avoid infinite recursion:
			// GenericDeleteOne calls a.LoadOne which would re-enter this callback.
			mongo.MONGOService.DeleteOne(d.GetID(), a.GetType().String())
			return nil, 410, errors.New("draft booking expired and deleted")
		}
		if (d.(*Booking).ExpectedEndDate) == nil {
			d.(*Booking).State = enum.FORGOTTEN
			utils.GenericRawUpdateOne(d, id, a)
		} else if d.(*Booking).State == enum.SCHEDULED && now.UTC().After(d.(*Booking).ExpectedStartDate) {
			d.(*Booking).State = enum.DELAYED
			utils.GenericRawUpdateOne(d, id, a)
		}
		return d, 200, nil
	}, a)
}

func (a *BookingMongoAccessor) GetExec(isDraft bool) func(utils.DBObject) utils.ShallowDBObject {
	return func(d utils.DBObject) utils.ShallowDBObject {
		now := time.Now()
		now = now.Add(time.Second * -60)
		if d.(*Booking).State == enum.DRAFT && now.UTC().After(d.(*Booking).ExpectedStartDate) {
			// Direct raw delete to avoid infinite recursion (same as LoadOne callback).
			mongo.MONGOService.DeleteOne(d.GetID(), a.GetType().String())
			return nil
		}
		if d.(*Booking).State == enum.SCHEDULED && now.UTC().After(d.(*Booking).ExpectedStartDate) {
			d.(*Booking).State = enum.DELAYED
			utils.GenericRawUpdateOne(d, d.GetID(), a)
		}
		return d
	}
}
