<?php

namespace classes;

use RuntimeException;

class customer_order_product_policy
{
    public static function assertOrderAllowsProduct(int $orderId, int $productId): void
    {
        $message = self::orderProductViolationMessage($orderId, $productId);
        if ($message !== null) {
            throw new RuntimeException($message);
        }
    }

    public static function orderProductViolationMessage(int $orderId, int $productId): ?string
    {
        $customerNumber = self::loadOrderCustomerNumber($orderId);
        if ($customerNumber === null) {
            return null;
        }
        $violation = (new customer_rule_product_restriction_service())
            ->violationForCustomerProduct($customerNumber, $productId);
        return $violation === null ? null : (string)$violation['message'];
    }

    private static function loadOrderCustomerNumber(int $orderId): ?int
    {
        global $db;

        if ($orderId < 1) {
            return null;
        }

        $result = $db->query("SELECT customer_id FROM orders WHERE id = {$orderId} LIMIT 1");
        if (!$result || $result->num_rows < 1) {
            return null;
        }

        $row = $result->fetch_assoc();
        $customerNumber = (int)($row['customer_id'] ?? 0);
        return $customerNumber > 0 ? $customerNumber : null;
    }

}
