package resolvedispatcher

import (
	"context"
	"fmt"
	"sync"

	"git.optclblast.xyz/draincloud/draincloud-core/internal/logger"
	"git.optclblast.xyz/draincloud/draincloud-core/internal/resolvers"
)

type ResolveDispatcher struct {
	m      sync.RWMutex
	router map[string]resolvers.Resolver
}

func New() *ResolveDispatcher {
	return &ResolveDispatcher{
		router: map[string]resolvers.Resolver{},
	}
}

func (d *ResolveDispatcher) RegisterResolver(
	ctx context.Context,
	resolverName string,
	resolver resolvers.Resolver,
) {
	d.m.Lock()
	defer d.m.Unlock()

	if _, ok := d.router[resolverName]; ok {
		logger.Fatal(ctx, fmt.Sprintf("resolver '%s' is already registered in router", resolverName))
	}

	d.router[resolverName] = resolver
}

func (d *ResolveDispatcher) GetResolver(name string) (resolvers.Resolver, error) {
	d.m.RLock()
	defer d.m.RUnlock()

	res, ok := d.router[name]
	if !ok {
		return nil, fmt.Errorf("resolver '%s' not found", name)
	}

	return res, nil
}
