<?php

namespace App\Queue\Failed;

use Illuminate\Queue\Failed\FailedJobProviderInterface;
use MongoDB\Client as MongoClient;

class MongoFailedJobProvider implements FailedJobProviderInterface
{
    protected $collection;

    public function __construct(MongoClient $mongo, $database = 'laravel')
    {
        $this->collection = $mongo->selectCollection($database, 'failed_jobs');
    }
    public function log($connection, $queue, $payload, $exception)
    {
        $this->collection->insertOne([
            'connection' => $connection,
            'queue' => $queue,
            'payload' => $payload,
            'exception' => (string) $exception,
            'failed_at' => now(),
        ]);
    }

    public function all()
    {
        return $this->collection->find()->toArray();
    }

    public function find($id)
    {
        return $this->collection->findOne(['_id' => new \MongoDB\BSON\ObjectId($id)]);
    }

    public function forget($id)
    {
        return $this->collection->deleteOne(['_id' => new \MongoDB\BSON\ObjectId($id)]);
    }

    public function flush()
    {
        return $this->collection->deleteMany([]);
    }
}
