"""Tests for factory functions."""

import pytest

from storage_core.clients.factory import (
    _first_env,
    create_s3_storage_client,
)
from storage_core.clients.s3 import S3StorageClient


class TestFirstEnv:
    def test_returns_first_set_var(self, monkeypatch):
        monkeypatch.setenv("A", "val_a")
        monkeypatch.setenv("B", "val_b")
        assert _first_env("A", "B") == "val_a"

    def test_skips_unset_vars(self, monkeypatch):
        monkeypatch.delenv("A", raising=False)
        monkeypatch.setenv("B", "val_b")
        assert _first_env("A", "B") == "val_b"

    def test_returns_none_when_none_set(self, monkeypatch):
        monkeypatch.delenv("A", raising=False)
        monkeypatch.delenv("B", raising=False)
        assert _first_env("A", "B") is None


class TestCreateS3StorageClient:
    def test_returns_s3_client_with_defaults(self):
        client = create_s3_storage_client(
            endpoint_url="http://localhost:9000",
            access_key="test",
            secret_key="test",
        )
        assert isinstance(client, S3StorageClient)

    def test_reads_from_env_vars(self, monkeypatch):
        monkeypatch.setenv("RUSTFS_ENDPOINT_URL", "http://rust:9000")
        monkeypatch.setenv("RUSTFS_ACCESS_KEY", "rk")
        monkeypatch.setenv("RUSTFS_SECRET_KEY", "rs")

        client = create_s3_storage_client()
        assert isinstance(client, S3StorageClient)
        assert client._endpoint_url == "http://rust:9000"

    def test_falls_back_to_s3_vars(self, monkeypatch):
        monkeypatch.delenv("RUSTFS_ENDPOINT_URL", raising=False)
        monkeypatch.delenv("RUSTFS_ACCESS_KEY", raising=False)
        monkeypatch.delenv("RUSTFS_SECRET_KEY", raising=False)
        monkeypatch.setenv("S3_ENDPOINT_URL", "http://s3:9000")
        monkeypatch.setenv("AWS_ACCESS_KEY_ID", "ak")
        monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "sk")

        client = create_s3_storage_client()
        assert isinstance(client, S3StorageClient)
        assert client._endpoint_url == "http://s3:9000"

    def test_get_alias_same(self):
        from storage_core.clients.factory import get_s3_storage_client
        assert get_s3_storage_client is create_s3_storage_client
