<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Query;

final class QueryResult
{
    public function __construct(
        private readonly array $request = [],
        private readonly array $rows = [],
        private readonly int $total = 0,
        private readonly int $returned = 0,
        private readonly float $queryTimeMs = 0.0,
        private readonly string $createdAt = ''
    ) {}

    public static function create(QueryRequest $request, array $rows, int $total, float $queryTimeMs): self
    {
        return new self($request->toArray(), $rows, $total, count($rows), $queryTimeMs, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (array) ($data['request'] ?? []),
            (array) ($data['rows'] ?? []),
            (int) ($data['total'] ?? 0),
            (int) ($data['returned'] ?? 0),
            (float) ($data['queryTimeMs'] ?? 0.0),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function total(): int { return $this->total; }
    public function returned(): int { return $this->returned; }
    public function rows(): array { return $this->rows; }

    public function toArray(): array
    {
        return [
            'request' => $this->request,
            'rows' => $this->rows,
            'total' => $this->total,
            'returned' => $this->returned,
            'queryTimeMs' => round($this->queryTimeMs, 3),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
