"""R2 storage backend configuration tests.

These assert the three R2-specific deviations from plain S3 that are silent
failures if wrong: region must be "auto", no ACL header, and path-style
addressing against the account endpoint. None of them touch the network —
presigning is a local HMAC.
"""

import pytest
from django.test import override_settings

from apps.core.storage_backends import R2MediaStorage

R2_SETTINGS = dict(
    R2_BUCKET_NAME="khub-test",
    R2_ENDPOINT_URL="https://acct123.r2.cloudflarestorage.com",
    R2_ACCESS_KEY_ID="testkey",
    R2_SECRET_ACCESS_KEY="testsecret",
    R2_URL_EXPIRY=300,
)


@pytest.fixture
def storage():
    with override_settings(**R2_SETTINGS):
        yield R2MediaStorage()


def test_region_is_auto(storage):
    """A real AWS region name makes SigV4 produce a signature R2 rejects."""
    assert storage.region_name == "auto"


def test_no_acl(storage):
    """R2 rejects the S3 ACL header; objects must stay private."""
    assert storage.default_acl is None
    assert "ACL" not in storage.object_parameters


def test_does_not_overwrite(storage):
    """Django's contract is to suffix a colliding name, not replace the object."""
    assert storage.file_overwrite is False


def test_url_is_presigned_against_account_endpoint(storage):
    url = storage.url("hr/employee_documents/contract.pdf")
    assert url.startswith("https://acct123.r2.cloudflarestorage.com/")
    # Path-style: bucket appears in the path, not as a subdomain.
    assert "/khub-test/hr/employee_documents/contract.pdf" in url
    assert "X-Amz-Signature=" in url
    assert "X-Amz-Expires=300" in url


def test_url_expiry_is_configurable(storage):
    with override_settings(**{**R2_SETTINGS, "R2_URL_EXPIRY": 60}):
        assert "X-Amz-Expires=60" in R2MediaStorage().url("a.txt")


@override_settings(
    STORAGES={
        "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
        "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"},
    }
)
def test_filesystem_remains_default_without_r2_env():
    """Media must stay local unless R2 is fully configured."""
    from django.conf import settings

    assert settings.STORAGES["default"]["BACKEND"].endswith("FileSystemStorage")
