"""Cloudflare R2 storage backend for user-uploaded media.

R2 speaks the S3 API, so django-storages' S3Boto3Storage works against it with
three deviations that are easy to get wrong:

1. Region must be "auto". R2 has no regions; boto3 still requires the field, and
   a real AWS region name makes SigV4 compute a signature R2 rejects with 401.
2. No ACLs. R2 ignores/rejects the S3 ACL header, so object_parameters must not
   carry one and the bucket must never be assumed world-readable.
3. Addressing is path-style against the account endpoint
   (https://<account_id>.r2.cloudflarestorage.com), not virtual-host style.

Objects are private. Reads go through presigned GET URLs whose lifetime is
R2_URL_EXPIRY seconds — short enough that a leaked URL expires quickly, long
enough for a browser to finish a large download. Presigning is a local HMAC over
the credentials, so `.url` costs no network round-trip.

Note deliberately NOT solved here: keys still come from each model's upload_to,
which today carries no organization prefix, and a presigned URL authorizes
whoever holds it. Tenant isolation is enforced by the API layer that hands out
the URL, not by this backend. Moving the bytes to R2 does not by itself make one
org's uploads unreachable to another.
"""

from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage


class R2MediaStorage(S3Boto3Storage):
    """Private R2 bucket for MEDIA files, served via presigned URLs."""

    # Signature must be v4; R2 does not accept v2.
    signature_version = "s3v4"
    addressing_style = "path"
    # R2 has no ACL concept — sending one is rejected.
    default_acl = None
    object_parameters = {"CacheControl": "private, max-age=0, no-store"}
    # Never silently clobber: Django's storage contract is to suffix a colliding
    # name, and overwriting would let one upload replace an unrelated file that
    # happens to share a key.
    file_overwrite = False
    querystring_auth = True

    def __init__(self, **kwargs):
        kwargs.setdefault("bucket_name", settings.R2_BUCKET_NAME)
        kwargs.setdefault("endpoint_url", settings.R2_ENDPOINT_URL)
        kwargs.setdefault("access_key", settings.R2_ACCESS_KEY_ID)
        kwargs.setdefault("secret_key", settings.R2_SECRET_ACCESS_KEY)
        kwargs.setdefault("region_name", "auto")
        kwargs.setdefault("querystring_expire", settings.R2_URL_EXPIRY)
        super().__init__(**kwargs)
