import base64
import hmac
from hashlib import sha256
from urllib.parse import parse_qs, urlparse

from dsg_core.core import s3


def test_generate_signed_url_custom_domain_uses_download_hmac_secret(monkeypatch):
    monkeypatch.setattr(
        s3.settings.bucket_storage,
        "public_download_url",
        "https://core-downloads.local.datasdrapps.com",
    )
    monkeypatch.setattr(
        s3.settings.bucket_storage,
        "download_hmac_secret",
        "sc+HqbWm48Xhplzm+bYJmuYvDGj2W5rhBW6Wue2NUyw=",
    )
    monkeypatch.setattr(s3.time, "time", lambda: 1_777_458_771)

    url = s3.generate_signed_url(
        "dsg-core/reports/0030d435-a283-5ff4-ba01-c1d28bbbcfa7/Codelists_20260427.csv",
        "local-dev",
        file_name="my report.csv",
        content_type="text/csv",
    )

    parsed_url = urlparse(url)
    query = parse_qs(parsed_url.query)
    expected_signing_payload = (
        "/dsg-core/reports/0030d435-a283-5ff4-ba01-c1d28bbbcfa7/"
        "Codelists_20260427.csv1777462371"
    )
    expected_signature = base64.b64encode(
        hmac.new(
            b"sc+HqbWm48Xhplzm+bYJmuYvDGj2W5rhBW6Wue2NUyw=",
            expected_signing_payload.encode("utf-8"),
            sha256,
        ).digest()
    ).decode("ascii")

    assert parsed_url.scheme == "https"
    assert parsed_url.netloc == "core-downloads.local.datasdrapps.com"
    assert (
        parsed_url.path == "/dsg-core/reports/0030d435-a283-5ff4-ba01-c1d28bbbcfa7/"
        "Codelists_20260427.csv"
    )
    assert query == {"verify": [f"1777462371-{expected_signature}"]}
