<?php
declare(strict_types=1);

namespace FreshCloud\Mail\Log;

use FreshCloud\Mail\PocketBaseAdapter\PocketBaseAdapter;
use FreshCloud\Mail\PocketBaseAdapter\CollectionAdapter;
use Throwable;

final class PbAuditDriver implements Driver
{
    private const MAX_RETRIES = 3;
    private const RETRY_DELAYS = [100, 500, 2000]; // ms

    public function __construct(
        private readonly PocketBaseAdapter $pb,
        private readonly string $collectionName = 'email_audit'
    ) {
    }

    public function write(LogEntry $entry): void
    {
        $data = $this->convertToAuditData($entry);
        
        for ($attempt = 0; $attempt < self::MAX_RETRIES; $attempt++) {
            try {
                $this->pb->collection($this->collectionName)->create($data);
                return;
            } catch (Throwable $e) {
                if ($attempt === self::MAX_RETRIES - 1) {
                    throw new \RuntimeException('Failed to write audit log after ' . self::MAX_RETRIES . ' attempts', 0, $e);
                }
                usleep(self::RETRY_DELAYS[$attempt] * 1000);
            }
        }
    }

    public function flush(): void
    {
        // No-op - writes are immediate
    }

    private function convertToAuditData(LogEntry $entry): array
    {
        return [
            'timestamp' => $entry->timestamp->format('Y-m-d H:i:s'),
            'level' => $entry->level->name,
            'message' => $entry->message,
            'context' => json_encode($entry->context),
            'user_id' => $entry->user_id,
            'account_id' => $entry->account_id,
            'action' => $entry->action,
            'source' => $entry->source
        ];
    }
}