package db

import (
	"fmt"

	"github.com/mongodb/mongo-tools/common/util"
	"go.mongodb.org/mongo-driver/v2/bson"
)

// OpTime represents the values to uniquely identify an oplog entry.
// An OpTime must always have a timestamp, but may or may not have a term.
// The hash is set uniquely up until (and including) version 4.0, but is set
// to zero in version 4.2+ with plans to remove it soon (see SERVER-36334).
type OpTime struct {
	Timestamp bson.Timestamp `json:"timestamp"`
	Term      *int64         `json:"term"`
}

// GetOpTimeFromOplogEntry returns an OpTime struct from the relevant fields in an Oplog struct.
func GetOpTimeFromOplogEntry(oplogEntry *Oplog) OpTime {
	return OpTime{
		Timestamp: oplogEntry.Timestamp,
		Term:      oplogEntry.Term,
	}
}

// OpTimeIsEmpty returns true if opTime is uninitialized, false otherwise.
func OpTimeIsEmpty(opTime OpTime) bool {
	return opTime == OpTime{}
}

// OpTimeLessThan returns true if lhs comes before rhs, false otherwise.
// We first check if both the terms exist. If they don't or they're equal,
// we compare just the timestamps.
func OpTimeLessThan(lhs OpTime, rhs OpTime) bool {
	if lhs.Term != nil && rhs.Term != nil {
		if *lhs.Term == *rhs.Term {
			return util.TimestampLessThan(lhs.Timestamp, rhs.Timestamp)
		}
		return *lhs.Term < *rhs.Term
	}

	return util.TimestampLessThan(lhs.Timestamp, rhs.Timestamp)
}

func (ot OpTime) String() string {
	if ot.Term != nil {
		return fmt.Sprintf("{Timestamp: %v, Term: %v}", ot.Timestamp, *ot.Term)
	}

	return fmt.Sprintf("{Timestamp: %v, Term: %v}", ot.Timestamp, nil)
}
