<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\src\UserInterface\Tables\ErrorTable;

use Plugin\tnt_stabila_shop\src\Abstracts\AbstractPaginatedData;
use Plugin\tnt_stabila_shop\src\Interfaces\PaginatedDataInterface;
use Plugin\tnt_stabila_shop\src\Models\Events;
use Plugin\tnt_stabila_shop\src\Repositories\DatabaseRepository;

final class ErrorTablePagination extends AbstractPaginatedData implements PaginatedDataInterface
{
    public function __construct(
        protected DatabaseRepository $database,
        protected int $currentPage = 1,
        protected readonly int $pageSize = 6,
    ) {
        parent::__construct($database);
        $this->init();
    }

    public function init(): void
    {
        $this->totalPages = $this->database->getTotalPages(Events::getTotalEntriesQuery(), $this->pageSize);
    }

    public function getPageSize(): int
    {
        return \count($this->getData());
    }

    /**
     * @return object{id: int, exceptionType: string, sdkVersion: string, filePath: string,
     *     functionName: string, template: string, shopVersion: string,
     *     severity: object{badgeType: string, value: string}, message: string, varDump: string,
     *     hash: string, createDate: \DateTime, reportLink: string, reportMaxDate: string, totalExecTime: float,
     *     shopLanguage: string, shopCurrency: string, cartCount: int, cartItems: string,
     *     deliveryCountry: string, invoiceCountry: string, taxRates: string[], userBrowser: string,
     *     userID: int}[]
     */
    public function getData(string $search = ''): array
    {
        $result = [];
        $where  = '';
        if ($search !== '') {
            $search = \strtolower($search);
            foreach (Events::getSearchableFields() as $column) {
                $where .= 'LOWER(' . $column . ') LIKE "%' . $search . '%" OR ';
            }
            $where = \substr($where, 0, -4);
        } else {
            $where = '1';
        }
        $events = $this->database->getPaginatedResults(Events::getPaginatedQuery(
            $this->getCurrentPage(),
            $this->pageSize,
            $where,
            'id DESC'
        ));
        if ($events === []) {
            return [];
        }
        foreach ($events as $event) {
            /** @var object{id: int, exceptionType: string, sdkVersion: string, extra: string, filePath: string, functionName: string, template: string, shopVersion: string, severity: string, message: string, varDump: string, hash: string, createDate: string} $event */
            $result[] = Events::transformData($event);
        }

        return $result;
    }
}
