<?php
/**
 * The single place where an order is judged against the withdrawal rules.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wc;

use DateTimeImmutable;
use DateTimeZone;
use SkyServers\Retragere\Core\DeadlineCalculator;
use SkyServers\Retragere\Core\EligibilityRules;
use SkyServers\Retragere\Wp\Settings;
use WC_Order;

/**
 * Three callers need the same verdict: the form, the account buttons and the
 * AJAX line loader. Building the rules three times invites them to drift apart.
 */
final class OrderEvaluation
{
    /**
     * @param WC_Order $order
     *
     * @return array<string,mixed>
     */
    public static function forOrder($order): array
    {
        $signal = B2bDetector::signal($order);

        $rules = new EligibilityRules(
            new DeadlineCalculator(Settings::windowDays()),
            Settings::eligibleStatuses(),
            !Settings::get('b2b_block')
        );

        $evaluation = $rules->evaluate(
            [
                'status'         => $order->get_status(),
                'reference_date' => OrderLookup::referenceDate($order),
                'is_b2b'         => B2bDetector::SIGNAL_NONE !== $signal,
            ],
            OrderItems::forOrder($order),
            new DateTimeImmutable('now', new DateTimeZone('UTC'))
        );

        $evaluation['b2b_signal'] = $signal;

        return $evaluation;
    }
}
