from pathlib import Path
from starlette.testclient import TestClient

from fmatch.saas.main import create_app
from fmatch.saas import settings as app_settings


def test_put_local_size_cap(tmp_path, monkeypatch):
    # Force local storage backend & small cap (16 bytes)
    monkeypatch.setattr(app_settings, "STORAGE_BACKEND", "local", raising=False)
    monkeypatch.setattr(app_settings, "LOCAL_STORAGE_PATH", str(tmp_path), raising=False)
    monkeypatch.setenv("FM_MAX_PUT_BYTES", "16")

    app = create_app()
    client = TestClient(app)

    # Presign
    r = client.post("/api/v2/uploads/presign", json={"content_type": "text/csv"})
    assert r.status_code == 200, r.text
    data = r.json()
    object_id = data["object_id"]
    put_url = data["put_url"]

    # Construct body larger than 16B
    body = b"a,b,c\n1,2,3\n4,5,6\n"

    r2 = client.put(put_url, data=body)
    assert r2.status_code == 413, r2.text

    # Ensure file is NOT present
    path = Path(app_settings.LOCAL_STORAGE_PATH) / object_id
    assert not path.exists()

