<?php

namespace Shopping\Validation;

use Shopping\Model\ShoppingProduct;

class ProductValidator {
    private array $fields;

    public function __construct(array $schema) {
        $this->fields = $schema['fields'];
    }

    public function validate(ShoppingProduct $product): ValidationResult {
        $errors = [];
        $data = $product->toArray();

        foreach ($this->fields as $fieldName => $field) {
            $value = $data[$fieldName] ?? null;

            // ❗ Required fields: presence is enforced by mapper,
            // NOT validated for non-null here
            if (!array_key_exists($fieldName, $data)) {
                $errors[] = "Schema violation: missing field key {$fieldName}";
                continue;
            }

            // Type validation only if value is present
            if ($value !== null && $value !== '') {

                if ($field['type'] === 'number' && !is_numeric($value)) {
                    $errors[] = "Invalid number for field: {$fieldName}";
                }

                if ($field['type'] === 'url' &&
                    !filter_var($value, FILTER_VALIDATE_URL)) {
                    $errors[] = "Invalid URL for field: {$fieldName}";
                }
            }
        }

        return new ValidationResult(empty($errors), $errors);
    }
}