<?php

declare( strict_types=1 );

namespace Soft_Tehnica\Freya_Sync_Service\Data\Woocommerce;

use WC_Product;

final class CartItemWrapper
{

    public function __construct( private readonly array $cartItem )
    {
    }

    public function getProductData(): WC_Product|null
    {
        $variationId = $this->cartItem['variation_id'] ?? 0;

        // Aici avem product variation, nu product, trebuie să facem query din păcate
        if ( $variationId > 0 ) {
            $productId = (int) $this->cartItem['product_id'] ?? 0;

            if ( $productId === 0 ) {
                return null;
            }

            $product = wc_get_product( $productId );

            return $product ?: null;
        }

        $ret = $this->cartItem['data'];

        if ( $ret instanceof WC_Product ) {
            return $ret;
        } else {
            return null;
        }
    }

    public function getQuantity(): int|null
    {
        if (
            !isset( $this->cartItem['quantity'] )
            || !is_float( $this->cartItem['quantity'] )
            || !is_int( $this->cartItem['quantity'] )
        ) {
            return null;
        }

        return (int) $this->cartItem['quantity'];
    }
}
