<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Service\Payment;

use Paysera\PrestashopPayments\Repository\OrderRepository;

if (!defined('_PS_VERSION_')) {
    exit;
}

class PaymentsListService
{
    public function __construct(
        private OrderRepository $orderRepository
    ) {
    }

    public function getPayments(array $params): array
    {
        $page = max(1, (int) ($params['page'] ?? 1));
        $perPage = max(1, min(100, (int) ($params['perPage'] ?? 20)));
        $orderBy = (string) ($params['orderBy'] ?? 'date_add');
        $orderDirection = (string) ($params['orderDirection'] ?? 'DESC');

        $filters = $this->buildFilters($params);

        return $this->orderRepository->getPayseraOrders(
            $page,
            $perPage,
            $orderBy,
            $orderDirection,
            $filters
        );
    }

    public function getPaymentDetails(int $paymentId): ?array
    {
        return $this->orderRepository->getPayseraOrderDetails($paymentId);
    }

    private function buildFilters(array $params): array
    {
        $filters = [];

        if (isset($params['search']) && $params['search'] !== '') {
            $filters['search'] = (string) $params['search'];
        }

        if (isset($params['orderId']) && $params['orderId'] !== '') {
            $filters['orderId'] = (string) $params['orderId'];
        }

        $date = $this->normalizeDateParam($params);
        if ($date !== null) {
            $filters['date'] = $date;
        }

        if (isset($params['customerEmail']) && $params['customerEmail'] !== '') {
            $filters['customerEmail'] = (string) $params['customerEmail'];
        }

        if (isset($params['customerName']) && $params['customerName'] !== '') {
            $filters['customerName'] = (string) $params['customerName'];
        }

        if (isset($params['paymentId']) && $params['paymentId'] !== '') {
            $filters['paymentId'] = (string) $params['paymentId'];
        }

        $status = $this->normalizeArrayOrString($params['status'] ?? null);
        if ($status !== null) {
            $filters['status'] = $status;
        }

        $paymentMethod = $this->normalizeArrayOrString($params['paymentMethod'] ?? null);
        if ($paymentMethod !== null) {
            $filters['paymentMethod'] = $paymentMethod;
        }

        return $filters;
    }

    /**
     * @param array<string, mixed> $params
     *
     * @return string|array{from?: string, to?: string}|null
     */
    private function normalizeDateParam(array $params)
    {
        $from = isset($params['dateFrom']) ? (string) $params['dateFrom'] : '';
        $to = isset($params['dateTo']) ? (string) $params['dateTo'] : '';

        if ($from !== '' || $to !== '') {
            $range = [];
            if ($from !== '') {
                $range['from'] = $from;
            }
            if ($to !== '') {
                $range['to'] = $to;
            }

            return $range;
        }

        if (isset($params['date']) && $params['date'] !== '') {
            return (string) $params['date'];
        }

        return null;
    }

    /**
     * @return string|array<int, string>|null
     */
    private function normalizeArrayOrString($value)
    {
        if (is_array($value)) {
            $values = array_values(array_filter(array_map(
                static fn ($v): string => (string) $v,
                $value
            ), static fn (string $v): bool => $v !== ''));

            return $values === [] ? null : $values;
        }

        if ($value === null || $value === '') {
            return null;
        }

        return (string) $value;
    }
}
