<?php

namespace Velis\Db;

use Phalcon\Di\DiInterface;
use Phalcon\Di\ServiceProviderInterface;
use UnexpectedValueException;
use Velis\App;
use Velis\Db\EntityHook\EntityHookExecutor;
use Velis\Model\DataObject\SnowflakeEntity;

class DbServiceProvider implements ServiceProviderInterface
{
    public function register(DiInterface $di): void
    {
        $di->set('db.profiler', function () use ($di) {
            $request = $di->get('request');
            $session = $di->get('session');

            return new Profiler($request, $session);
        });

        $di->setShared('db', function () use ($di) {
            $adapterClass = '\Velis\Db\\' . ucfirst(App::$config->get('db')->get('adapter'));

            return new $adapterClass();
        });

        $di->setShared(Db::class, function () {
            return App::$di['db'];
        });

        $di->setShared(EntityHookExecutor::class, function () use ($di) {
            return new EntityHookExecutor($di);
        });

        if (App::$config->has('snowflake')) {
            $di->set(Snowflake::class, function () {
                $config = App::$config->get('snowflake');

                return match ($config->get('driver')) {
                    SnowflakeDriver::Odbc->value => new SnowflakeOdbc(),
                    SnowflakeDriver::Pdo->value => new SnowflakePdo(),
                    SnowflakeDriver::PgMock->value => new PgSnowflakeMock($config->get('mock')),
                    default => throw new UnexpectedValueException('Unknown Snowflake driver'),
                };
            });

            $di->set('snowflake', function () {
                return App::getService(Snowflake::class);
            });

            SnowflakeEntity::init();
        }
    }
}
