<?php
/**
 * _             _       _
 * | |____      _| | __ _| |__
 * | '_ \ \ /\ / / |/ _` | '_ \
 * | |_) \ V  V /| | (_| | |_) |
 * |_.__/ \_/\_/ |_|\__,_|_.__/.
 *
 * @author    Bwlab di Luigi Massa <info@bwlab.it>
 * @copyright since 2014 Bwlab
 * @license   proprietary
 */

declare(strict_types=1);

namespace Bwlab\Withdrawal\Service;

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


use Bwlab\Withdrawal\Repository\WithdrawalCategoryConfigRepository;

class WithdrawalDeadlineCalculator
{
    public function __construct(
        private readonly WithdrawalCategoryConfigRepository $categoryConfigRepository,
        private readonly int $defaultDays,
    ) {
    }

    /**
     * Returns the number of withdrawal days for the given order products, or null if excluded.
     *
     * @param array<int, array{id_category_default: int}> $orderProducts
     */
    public function calculateDays(array $orderProducts, int $shopId): ?int
    {
        $minDays = $this->defaultDays;
        $excluded = false;

        foreach ($orderProducts as $product) {
            $categoryId = (int) ($product['id_category_default'] ?? 0);
            if ($categoryId === 0) {
                continue;
            }

            $config = $this->categoryConfigRepository->findByCategory($categoryId, $shopId);
            if ($config === null) {
                continue;
            }

            if ($config->isExcluded()) {
                $excluded = true;
                break;
            }

            $minDays = min($minDays, $config->getWithdrawalDays());
        }

        return $excluded ? null : $minDays;
    }

    public function calculateDeadline(\DateTimeInterface $referenceDate, int $days): \DateTimeInterface
    {
        $deadline = clone $referenceDate;
        if ($deadline instanceof \DateTime) {
            $deadline->modify("+{$days} days");
        } else {
            $deadline = \DateTime::createFromInterface($deadline);
            $deadline->modify("+{$days} days");
        }

        return $deadline;
    }
}
