<?php

namespace PortalPeople\virtualstock\models;

/**
 * Value object representing a VirtualStock product stock level.
 */
class StockLevel
{
    public string $productId          = '';
    public int $quantity           = 0;
    public string $availabilityStatus = '';

    /** @var array<string, mixed> */
    public array $raw = [];

    /**
     * Create from an API response array.
     *
     * @param array<string, mixed> $data
     */
    public static function fromArray(array $data): self
    {
        $s = new self();

        $s->productId          = (string) ($data['product_id'] ?? $data['id'] ?? '');
        $s->quantity           = (int)    ($data['quantity'] ?? $data['stock_quantity'] ?? $data['stock'] ?? 0);
        $s->availabilityStatus = (string) ($data['availability_status'] ?? $data['status'] ?? '');
        $s->raw                = $data;

        return $s;
    }

    /**
     * Serialize to an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'product_id'          => $this->productId,
            'quantity'            => $this->quantity,
            'availability_status' => $this->availabilityStatus,
        ];
    }

    /**
     * Returns true if the stock level indicates the product is available.
     * Considers quantity > 0 or an explicitly positive availability status.
     */
    public function isAvailable(): bool
    {
        if ($this->quantity > 0) {
            return true;
        }

        $status = strtolower(trim($this->availabilityStatus));

        return in_array($status, ['available', 'in_stock', 'in stock'], true);
    }
}
