package services

import (
	"errors"
	"fmt"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/connector"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/logger"
	"github.com/dexidp/dex/storage"
	"github.com/dexidp/dex/storage/memory"
	"github.com/dexidp/dex/storage/sql"
)

func InitStorage(conf *config.AppConfig) (storage.Storage, error) {
	var storageType storage.Storage
	var err error
	switch conf.StorageType {
	case "memory":
		storageType = memory.New(logger.L)
	case "sqlite":
		sqlconfig := sql.SQLite3{
			File: conf.StorageConfig.File,
		}
		storageType, err = sqlconfig.Open(logger.L)
		if err != nil {
			logger.L.Fatalf("Failed to initialize sqlite backend: %s", err.Error())
		}
	default:
		return storageType, fmt.Errorf("unsupported storage backend type: %s", conf.StorageType)
	}
	return storageType, nil
}

func AddDefaultBackend(s storage.Storage) error {
	if err := s.CreateConnector(connector.RefuseAllConnectorConfig); err != nil && !errors.Is(err, storage.ErrAlreadyExists) {
		return fmt.Errorf("failed to add default backend: %w", err)
	}
	return nil
}
