<?php

namespace App\Domains\AI\Validators;

class OrderDraftValidator
{
    public function validate(array $payload, array $context): array
    {
        $warnings = $payload['warnings'] ?? [];
        $items = array_values(array_filter($payload['items'] ?? [], function ($item) {
            return is_array($item)
                && ! empty($item['product_name'] ?? null)
                && (int) ($item['quantity'] ?? 0) > 0;
        }));

        if (($payload['order_signal_detected'] ?? false) && empty($items)) {
            $warnings[] = 'Order intent was detected but no valid catalog item could be extracted.';
        }

        $state = empty($warnings) ? 'pass' : 'pass_with_warning';

        if (($payload['order_signal_detected'] ?? false) && empty($items)) {
            $state = 'fail';
        }

        return [
            'state' => $state,
            'warnings' => array_values(array_unique($warnings)),
        ];
    }
}
