package store

import (
	"context"
	"errors"
	"fmt"
	"time"

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

// PasswordReset is a one-shot token (§11.22), reaped by TTL index.
type PasswordReset struct {
	Token     string    `bson:"_id"`
	UserID    string    `bson:"userId"`
	ExpiresAt time.Time `bson:"expiresAt"`
}

func (s *Store) CreatePasswordReset(ctx context.Context, token, userID string, ttl time.Duration) error {
	_, err := s.DB.Collection("passwordResets").InsertOne(ctx, PasswordReset{
		Token: token, UserID: userID, ExpiresAt: time.Now().UTC().Add(ttl),
	})
	if err != nil {
		return fmt.Errorf("create password reset: %w", err)
	}
	return nil
}

// ConsumePasswordReset returns the userId for a live token and deletes it
// atomically (single use).
func (s *Store) ConsumePasswordReset(ctx context.Context, token string) (string, error) {
	var pr PasswordReset
	err := s.DB.Collection("passwordResets").FindOneAndDelete(ctx, bson.M{
		"_id":       token,
		"expiresAt": bson.M{"$gt": time.Now().UTC()},
	}).Decode(&pr)
	if errors.Is(err, mongo.ErrNoDocuments) {
		return "", ErrNotFound
	}
	if err != nil {
		return "", fmt.Errorf("consume password reset: %w", err)
	}
	return pr.UserID, nil
}
