package services

import (
	"encoding/json"
	"fmt"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
	dex_server "github.com/dexidp/dex/server"
	"github.com/dexidp/dex/storage"
)

func CreateConnector(backend *config.BackendConfig, dexConf *dex_server.Config, connectorIDs []string) error {
	for _, id := range connectorIDs {
		if id == backend.ID {
			return nil
		}
	}

	backendConfJson, err := json.Marshal(backend.Config)
	if err != nil {
		return fmt.Errorf("failed to serialize oidc config for backend %q: %s", backend.Name, err.Error())
	}
	return dexConf.Storage.CreateConnector(storage.Connector{
		ID:     backend.ID,
		Name:   backend.Name,
		Type:   string(backend.Type),
		Config: backendConfJson,
	})
}
