<?php

namespace PortalPeople\virtualstock\services;

use PortalPeople\virtualstock\components\VirtualStockClient;
use PortalPeople\virtualstock\models\Product;
use PortalPeople\virtualstock\models\StockLevel;
use yii\base\Component;

/**
 * REST service for VirtualStock product and stock operations.
 */
class ProductService extends Component
{
    public VirtualStockClient $client;

    /**
     * List products, optionally filtered.
     *
     * @param array<string, mixed> $filters  e.g. ['supplier_code' => 'TSL', 'limit' => 50]
     * @return Product[]
     */
    public function listProducts(array $filters = []): array
    {
        $data = $this->client->listProducts($filters);
        $products = [];

        $items = $data['products'] ?? $data['results'] ?? $data;

        if (is_array($items)) {
            foreach ($items as $item) {
                if (is_array($item)) {
                    $products[] = Product::fromArray($item);
                }
            }
        }

        return $products;
    }

    /**
     * Retrieve a single product by its supplier SKU / product number.
     */
    public function getProduct(string $supplierSku): Product
    {
        $data = $this->client->getProduct($supplierSku);
        return Product::fromArray($data);
    }

    /**
     * Retrieve stock level for a product by its supplier SKU / product number.
     */
    public function getStockLevel(string $supplierSku): StockLevel
    {
        $data = $this->client->getProductStock($supplierSku);
        return StockLevel::fromArray($data);
    }

    /**
     * Search products by keyword.
     *
     * @param array<string, mixed> $extra  Additional filter parameters
     * @return Product[]
     */
    public function searchProducts(string $keyword, array $extra = []): array
    {
        return $this->listProducts(array_merge(['search' => $keyword], $extra));
    }
}
