package verificationimp

import (
	"context"

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

type ConfirmationStore struct {
	db verification.DB
}

func NewStore(db verification.DB) *ConfirmationStore {
	return &ConfirmationStore{db: db}
}

func (s *ConfirmationStore) Create(
	ctx context.Context,
	request *verification.Request,
) (verificationCode string, err error) {
	return s.db.Create(ctx, request)
}

func (s *ConfirmationStore) Verify(
	ctx context.Context,
	accountRef bson.ObjectID,
	purpose model.VerificationPurpose,
	code string,
) (target string, err error) {
	t, err := s.db.Consume(ctx, accountRef, purpose, code)
	if err != nil {
		return "", err
	}
	if t.Purpose != purpose {
		return "", merrors.DataConflict("token has different verificaton purpose")
	}
	return t.Target, nil
}
