import io
import pytest
from django.core.files.base import ContentFile
from django.conf import settings
from django_s3_aws.storage import S3AWSStorage


@pytest.mark.django_db
class TestS3AWSStorage:

    def setup_method(self):
        # Configuración para cada test
        settings.AWS_STORAGE_BUCKET_NAME = "test-bucket"
        settings.AWS_REGION = "us-east-1"
        # ⚠️ En un entorno real usarías moto3 para mockear S3
        self.storage = S3AWSStorage()

    def test_storage_init_without_bucket(self, settings):
        settings.AWS_STORAGE_BUCKET_NAME = None
        with pytest.raises(ValueError):
            S3AWSStorage()

    def test_save_and_exists(self):
        file_content = ContentFile(b"hello world", name="test.txt")
        name = self.storage._save("test.txt", file_content)
        assert name == "test.txt"
        assert self.storage.exists("test.txt") is True

    def test_delete(self):
        # Simulación de guardado
        file_content = io.BytesIO(b"delete me")
        self.storage._save("delete.txt", file_content)

        # Eliminar
        self.storage.delete("delete.txt")
        # Como no hay mock, solo validamos que no rompa
        assert True

    def test_url_generation(self):
        url = self.storage.url("test.txt")
        assert url.startswith("https://")
        assert "test-bucket" in url

    def test_presigned_url(self):
        url = self.storage.generate_presigned_url("test.txt", expiration=600)
        assert "X-Amz-Signature" in url
