<?php
declare(strict_types=1);

namespace FreshCloud\Mail\PocketBaseAdapter;

use Ramsey\Uuid\Uuid;

final class InMemoryPb implements PocketBaseAdapter
{
    private array $stores = [];
    private array $failures = [];

    public function __construct()
    {
    }

    public function failNext(int $count): void
    {
        $this->failures[] = $count;
    }

    public function collection(string $name): CollectionAdapter
    {
        if (!isset($this->stores[$name])) {
            $this->stores[$name] = new InMemoryCollectionAdapter();
        }
        return $this->stores[$name];
    }
}

final class InMemoryCollectionAdapter implements CollectionAdapter
{
    private array $records = [];

    public function create(array $data): array
    {
        $record = array_merge([
            'id' => Uuid::uuid4()->toString(),
            'created' => date('Y-m-d H:i:s'),
        ], $data);
        
        $this->records[] = $record;
        return $record;
    }

    public function getOne(string $id): array
    {
        foreach ($this->records as $record) {
            if ($record['id'] === $id) {
                return $record;
            }
        }
        throw new \RuntimeException("Record not found: {$id}");
    }

    public function getList(int $page, int $perPage, array $opts = []): array
    {
        return array_slice($this->records, ($page - 1) * $perPage, $perPage);
    }

    public function update(string $id, array $data): array
    {
        foreach ($this->records as &$record) {
            if ($record['id'] === $id) {
                $record = array_merge($record, $data);
                return $record;
            }
        }
        throw new \RuntimeException("Record not found: {$id}");
    }

    public function delete(string $id): void
    {
        foreach ($this->records as $i => $record) {
            if ($record['id'] === $id) {
                unset($this->records[$i]);
                return;
            }
        }
        throw new \RuntimeException("Record not found: {$id}");
    }
}