<?php

declare(strict_types=1);

namespace KupShop\CatalogElasticBundle\Elastica;

use Elastica\Multi\ResultSet as MultiResultSet;
use Elastica\ResultSet;
use KupShop\CatalogBundle\Search\Exception\FulltextException;

class ErrorWrap
{
    public static function extractError(MultiResultSet|ResultSet $resultSet): ?FulltextException
    {
        $allResultSets = match (true) {
            $resultSet instanceof MultiResultSet => $resultSet->getResultSets(),
            default => [$resultSet],
        };

        $errors = [];
        $messages = [];
        foreach ($allResultSets as $rs) {
            $response = $rs->getResponse();

            if ($response->isOk()) {
                continue;
            }

            $messages[] = $response->getError();

            if (is_array($error = $response->getFullError())) {
                foreach (($error['failed_shards'] ?? []) as $errorIndex => $errorShard) {
                    $errorReason = $errorShard['reason'] ?? [];
                    if (!is_array($errorReason)) {
                        continue;
                    }

                    $errors[$errorIndex] = $errorReason;
                }
            }
        }

        if (empty($errors)) {
            return null;
        }

        return new FulltextException(
            implode(', ', $messages), [
                'errors' => $errors,
            ]);
    }
}
