package human

import (
	"context"
	"errors"

	"github.com/flowy-live/llink/internal/utils"
	"github.com/jackc/pgx/v5/pgxpool"
)

var ErrNotFound = errors.New("human not found")

type Service interface {
	GetOrCreateByEmail(ctx context.Context, email string) (*Human, error)
	// GetByEmail returns ErrNotFound if no human found
	GetByEmail(ctx context.Context, email string) (*Human, error)
}

type serviceImpl struct {
	repo repository
}

func NewService(pool *pgxpool.Pool) Service {
	return &serviceImpl{repo: newRepository(pool)}
}

func (s *serviceImpl) GetOrCreateByEmail(ctx context.Context, email string) (*Human, error) {
	email, err := utils.NormalizeEmail(email)
	if err != nil {
		return nil, err
	}

	h, err := s.repo.getByEmail(ctx, email)
	if err != nil {
		if errors.Is(err, errNotFound) {
			return s.repo.create(ctx, email)
		}
		return nil, err
	}
	return h, nil
}

func (s *serviceImpl) GetByEmail(ctx context.Context, email string) (*Human, error) {
	email, err := utils.NormalizeEmail(email)
	if err != nil {
		return nil, err
	}

	h, err := s.repo.getByEmail(ctx, email)
	if errors.Is(err, errNotFound) {
		return nil, ErrNotFound
	}
	return h, err
}
