<?php

namespace PortalPeople\virtualstock\models;

/**
 * Value object representing a VirtualStock product (supplier catalogue entry).
 */
class Product
{
    public string $id          = '';
    public string $supplierSku = '';
    public string $name        = '';
    public string $description = '';
    public float $unitPrice   = 0.0;
    public int $leadTime    = 0;
    public string $supplierCode = '';
    public bool $active      = true;

    /** @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
    {
        $p = new self();

        $p->id           = (string) ($data['id'] ?? $data['product_id'] ?? '');
        $p->supplierSku  = (string) ($data['supplier_sku'] ?? $data['supplier_product_no'] ?? $data['sku'] ?? '');
        $p->name         = (string) ($data['name'] ?? $data['product_name'] ?? '');
        $p->description  = (string) ($data['description'] ?? '');
        $p->unitPrice    = (float)  ($data['unit_price'] ?? $data['price'] ?? 0.0);
        $p->leadTime     = (int)    ($data['lead_time'] ?? $data['lead_time_days'] ?? 0);
        $p->supplierCode = (string) ($data['supplier_code'] ?? '');
        $p->active       = (bool)   ($data['active'] ?? $data['is_active'] ?? true);
        $p->raw          = $data;

        return $p;
    }

    /**
     * Serialize to an array suitable for API payloads or local persistence.
     *
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'id'           => $this->id,
            'supplier_sku' => $this->supplierSku,
            'name'         => $this->name,
            'description'  => $this->description,
            'unit_price'   => $this->unitPrice,
            'lead_time'    => $this->leadTime,
            'supplier_code' => $this->supplierCode,
            'active'       => $this->active,
        ];
    }

    /**
     * Returns true if the product has enough data to be useful.
     */
    public function isIdentifiable(): bool
    {
        return $this->id !== '' && $this->supplierSku !== '';
    }
}
