<?php

namespace app\service\Search;

use OpenSearch\Client;
use OpenSearch\ClientBuilder;

class OpenSearchClientFactory
{
    public function make(?array $config = null): Client
    {
        $config = $config ?? config('opensearch.default', []);

        $builder = ClientBuilder::create()
            ->setHosts($config['hosts'] ?? ['http://127.0.0.1:9200'])
            ->setSSLVerification((bool) ($config['ssl_verify'] ?? true))
            ->setConnectionParams([
                'client' => [
                    'timeout' => (float) ($config['timeout'] ?? 30),
                    'connect_timeout' => (float) ($config['connect_timeout'] ?? 5),
                ],
            ]);

        $username = trim((string) ($config['username'] ?? ''));
        $password = trim((string) ($config['password'] ?? ''));
        if ($username !== '' && $password !== '') {
            $builder->setBasicAuthentication($username, $password);
        }

        return $builder->build();
    }
}
