<?php

namespace Khatfield\Tautulli;

use Illuminate\Support\Collection;

/**
 * Represents a single page of results from a paginated Tautulli endpoint.
 *
 * Tautulli uses DataTables-style pagination: results include
 * `recordsTotal`, `recordsFiltered`, and `data`.
 */
class PaginatedResponse
{
    public function __construct(
        /** Raw items for this page. */
        public readonly Collection $data,

        /** Total records in the dataset (unfiltered). */
        public readonly int $recordsTotal,

        /** Total records after any server-side filtering. */
        public readonly int $recordsFiltered,

        /** Zero-based offset used for this page. */
        public readonly int $start,

        /** Number of items requested per page. */
        public readonly int $length,
    ) {}

    /** The current (1-based) page number. */
    public function currentPage(): int
    {
        return $this->length > 0 ? (int) floor($this->start / $this->length) + 1 : 1;
    }

    /** Total number of pages. */
    public function lastPage(): int
    {
        return $this->length > 0 ? (int) ceil($this->recordsFiltered / $this->length) : 1;
    }

    public function hasMorePages(): bool
    {
        return $this->currentPage() < $this->lastPage();
    }

    /** The offset to pass for the next page, or null if this is the last page. */
    public function nextPageStart(): ?int
    {
        if (! $this->hasMorePages()) {
            return null;
        }

        return $this->start + $this->length;
    }

    public function toArray(): array
    {
        return [
            'data'              => $this->data->toArray(),
            'records_total'     => $this->recordsTotal,
            'records_filtered'  => $this->recordsFiltered,
            'current_page'      => $this->currentPage(),
            'last_page'         => $this->lastPage(),
            'per_page'          => $this->length,
            'from'              => $this->start,
            'has_more_pages'    => $this->hasMorePages(),
        ];
    }
}
