package orm

import (
	"context"
	"reflect"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

const COUNTER_COL = "@counters"

type Counter struct {
	Current    any    `bson:"current"`
	Collection string `bson:"collection"`
}

func getLastInColl(cname string, id interface{}) interface{} {
	var opts = options.FindOne()

	switch id.(type) {
	case int, int64, int32, uint, uint32, uint64, bson.ObjectID:
		opts.SetSort(bson.M{"_id": -1})
	case string:
		opts.SetSort(bson.M{"createdAt": -1})
	default:
		panic(ErrUnsupportedID)
	}

	var cnt Counter
	if !reflect.ValueOf(id).IsZero() {
		return id
	}
	if err := DB.Collection(COUNTER_COL).FindOne(context.TODO(), bson.M{
		"collection": cname,
	}, opts).Decode(&cnt); err != nil {
		cnt = Counter{
			Current: id,
		}
		cnt.Collection = cname
	}
	return cnt.Current
}