<?php

declare (strict_types = 1);
namespace Brightfern\Transmission;

// Send-side types are premium-only and referenced by fully-qualified name
// inside the send methods below. Deliberately no `use` imports: those would
// survive into the free build as dangling references to a stripped path.
/**
 * An in-memory Access Point used for local development, the test suite, and as
 * a safe default before real credentials are entered. It "accepts" everything,
 * remembers what it was sent, and can be primed with inbound documents to
 * exercise the receive path end-to-end without a network.
 *
 * Because it implements the same interface as {@see StorecoveProvider}, the
 * entire SEND/RECEIVE pipeline can be demonstrated and tested with no provider
 * account — which is exactly how the README's "send AND receive a test invoice"
 * checklist works offline.
 */
final class MockProvider implements AccessPointProvider {
    /** @var \Brightfern\Transmission\Send\OutboundDocument[] Premium build only. */
    public array $sent = array();

    /** @var InboundInvoice[] Primed inbound documents returned by poll(). */
    private array $inbox;

    private int $counter = 0;

    /**
     * @param InboundInvoice[] $inbox
     */
    public function __construct( array $inbox = array() ) {
        $this->inbox = $inbox;
    }

    public function id() : string {
        return 'mock';
    }

    public function label() : string {
        return 'Mock (sandbox, no network)';
    }

    public function supportsReceiving() : bool {
        return true;
    }

    public function handleIncoming( array $payload ) : ?InboundInvoice {
        if ( !isset( $payload['xml'] ) || !is_string( $payload['xml'] ) ) {
            return null;
        }
        return new InboundInvoice(
            (string) ($payload['id'] ?? 'mock-in-' . md5( $payload['xml'] )),
            (string) ($payload['sender'] ?? ''),
            (string) ($payload['recipient'] ?? ''),
            (string) ($payload['documentType'] ?? 'invoice'),
            $payload['xml'],
            (string) ($payload['receivedAt'] ?? ''),
            'peppol-bis-billing-3.0',
            $payload
        );
    }

    public function poll() : array {
        $items = $this->inbox;
        $this->inbox = array();
        // Drain once, like a real polling cursor.
        return $items;
    }

}
