<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Queue\Failed\FailedJobProviderInterface;
use MongoDB\Client as MongoClient;
use App\Queue\Failed\MongoFailedJobProvider;
use App\Queue\MongoDatabaseQueue;
use Illuminate\Queue\QueueManager;
class MongoQueueServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
         // Register MongoDB client as singleton using Laravel's DB config
        // $this->app->singleton('mongodb', function () {
        //     $config = Config::get('database.connections.mongodb');

        //     $host = $config['host'] ?? '127.0.0.1';
        //     $port = $config['port'] ?? 27017;
        //     $database = $config['database'] ?? 'your_db';
        //     $username = $config['username'] ?? null;
        //     $password = $config['password'] ?? null;

        //     $uri = 'mongodb://';

        //     if ($username && $password) {
        //         $uri .= "{$username}:{$password}@";
        //     }

        //     $uri .= "{$host}:{$port}/{$database}";

        //     return new MongoClient($uri);
        // });

        
        // Register MongoDB-based queue driver
        // $this->app->afterResolving(QueueManager::class, function (QueueManager $manager) {
        //     $manager->addConnector('mongodb', function () {
            //         return function ($config) {
                //             $mongo = app('mongodb');

                //             return new MongoDatabaseQueue(
        //                 $mongo,
        //                 $config['collection'] ?? 'jobs',
        //                 $config['queue'] ?? 'default'
        //             );
        //         };
        //     });
        // });
        
        $this->app->singleton('mongodb', function ($app) {
            return $app['db']->connection(); // returns MongoDB connection
        });

        $this->app->afterResolving(QueueManager::class, function (QueueManager $manager) {
            $manager->addConnector('mongodb', function () {
                return new \App\Queue\Connectors\MongoConnector;
            });
        });
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // $this->app['queue']->extend('mongodb', function () {
        //     return new MongoDatabaseQueue(
        //         app('mongodb'),
        //         'jobs',
        //         'default'
        //     );
        // });

        // $this->app['queue']->extend('mongodb', function ($app, $config) {
        //     $mongo = $app->make('mongodb');

        //     return new MongoDatabaseQueue($mongo,$config['collection'] ?? 'jobs',$config['queue'] ?? 'default');
        // });
    }
}
