<?php

namespace App\Domains\AI\Validators;

class ReplySuggestionSafetyValidator
{
    public function validate(array $payload, array $context): array
    {
        $warnings = $payload['warnings'] ?? [];
        $replyText = trim((string) ($payload['reply_text'] ?? ''));

        if ($replyText === '') {
            return [
                'state' => 'fail',
                'warnings' => ['Could not generate a safe suggestion.'],
            ];
        }

        if (mb_strlen($replyText) > 800) {
            return [
                'state' => 'fail',
                'warnings' => ['Reply suggestion is too long to be safely reviewed.'],
            ];
        }

        $hasPricingContext = ! empty($context['relevant_products'][0]['price'] ?? null);
        $mentionsDiscount = preg_match('/discount|خصم|free shipping|شحن مجاني/i', $replyText) === 1;

        if ($mentionsDiscount && empty($context['policy_snippets']['pricing_rules'] ?? null)) {
            $warnings[] = 'Discount or pricing policy should be verified before sending.';
        }

        if (! $hasPricingContext && preg_match('/\d/', $replyText) === 1) {
            $warnings[] = 'Numeric details should be verified against pricing or policy data.';
        }

        return [
            'state' => empty($warnings) ? 'pass' : 'pass_with_warning',
            'warnings' => array_values(array_unique($warnings)),
        ];
    }
}
