<?php

declare(strict_types=1);

namespace Apexl\Vault\Connections;

use Apexl\Vault\Exceptions\MongoUnsupportedException;
use Apexl\Vault\Interfaces\ConnectionInterface;

final class MongoConnection implements ConnectionInterface
{
    public function __construct(
        private readonly mixed $client,
        private readonly int $lastInsertId = 0,
    ) {}

    public function handle(): mixed
    {
        return $this->client;
    }

    /**
     * Mongo issues no ids of its own here — the counters strategy assigns them before
     * the write — so this reports what was last assigned rather than reading it back.
     */
    public function lastInsertId(): int
    {
        return $this->lastInsertId;
    }

    /**
     * Mongo transactions need a replica set or a sharded cluster, and silently running
     * $work without one would promise atomicity this connection cannot deliver.
     */
    public function transaction(callable $work): mixed
    {
        throw new MongoUnsupportedException(
            'transaction() needs a replica set; run the work without one or use a '
            . 'single-document update, which is already atomic'
        );
    }

    public function inTransaction(): bool
    {
        return false;
    }
}
