package confirmationdb

import (
	"context"
	"time"

	"github.com/tech/sendico/pkg/db/repository"
	"github.com/tech/sendico/pkg/db/repository/builder"
	"github.com/tech/sendico/pkg/model"
	"go.mongodb.org/mongo-driver/v2/bson"
)

func (db *ConfirmationDB) FindActive(ctx context.Context, accountRef bson.ObjectID, destination string, target model.ConfirmationTarget, now int64) (*model.ConfirmationCode, error) {
	var res model.ConfirmationCode
	query := repository.Query().
		Filter(repository.Field(fieldAccountRef), accountRef).
		Filter(repository.Field(fieldDestination), destination).
		Filter(repository.Field(fieldTarget), target).
		Filter(repository.Field(fieldUsed), false).
		Comparison(repository.Field(fieldExpiresAt), builder.Gt, time.Unix(now, 0))

	if err := db.FindOne(ctx, query, &res); err != nil {
		return nil, err
	}
	return &res, nil
}
