import io

import pytest
from PIL import Image

import app.api.v1.endpoints.uploads as uploads_module
from app.core import security
from app.core.config import settings
from app.models.user import User, UserRole
from app.utils.phone import normalize_ethiopian_phone

PHONE = "0964000001"
SEED_PIN = "111111"


def _seed_user(db_session):
    normalized = normalize_ethiopian_phone(PHONE)
    user = User(
        phone=normalized,
        name="An Uploader",
        email="uploader@example.com",
        role=UserRole.CUSTOMER.value,
        pin_hash=security.hash_pin(SEED_PIN),
        is_phone_verified=True,
        is_email_verified=True,
    )
    db_session.add(user)
    db_session.commit()
    return user


def _login(client):
    resp = client.post(
        "/api/v1/auth/login", json={"identifier": PHONE, "pin": SEED_PIN}
    )
    assert resp.status_code == 200, resp.text
    return resp.json()["access_token"]


@pytest.fixture()
def customer_token(client, db_session):
    _seed_user(db_session)
    return _login(client)


def _auth_headers(token: str) -> dict:
    return {"Authorization": f"Bearer {token}"}


def _png_bytes() -> bytes:
    buf = io.BytesIO()
    Image.new("RGB", (4, 4), color="red").save(buf, format="PNG")
    return buf.getvalue()


def test_upload_valid_image_succeeds(client, customer_token, monkeypatch):
    monkeypatch.setattr(
        uploads_module,
        "upload_image",
        lambda file, folder: "https://cdn.example.com/x.png",
    )
    resp = client.post(
        "/api/v1/uploads/image",
        files={"file": ("photo.png", _png_bytes(), "image/png")},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["url"] == "https://cdn.example.com/x.png"


def test_upload_requires_auth(client):
    resp = client.post(
        "/api/v1/uploads/image",
        files={"file": ("photo.png", _png_bytes(), "image/png")},
    )
    assert resp.status_code == 401  # no Authorization header at all


def test_upload_rejects_disallowed_content_type(client, customer_token):
    resp = client.post(
        "/api/v1/uploads/image",
        files={"file": ("doc.pdf", b"%PDF-1.4", "application/pdf")},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 400


def test_upload_rejects_spoofed_content_type(client, customer_token):
    """Client claims image/png via Content-Type, but the bytes aren't
    actually a PNG — must be rejected by the real content check even
    though the header lied."""
    resp = client.post(
        "/api/v1/uploads/image",
        files={"file": ("fake.png", b"not actually a png file", "image/png")},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 400


def test_upload_rejects_oversized_file(client, customer_token, monkeypatch):
    monkeypatch.setattr(settings, "max_upload_size_bytes", 10)
    resp = client.post(
        "/api/v1/uploads/image",
        files={"file": ("photo.png", _png_bytes(), "image/png")},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 413


def test_upload_is_rate_limited_per_user(client, customer_token, monkeypatch):
    """Checked before the real Cloudinary call — each upload costs
    money regardless of whether it ends up used anywhere."""
    monkeypatch.setattr(
        uploads_module,
        "upload_image",
        lambda file, folder: "https://cdn.example.com/x.png",
    )
    limit = settings.upload_rate_limit_max_attempts
    for _ in range(limit):
        resp = client.post(
            "/api/v1/uploads/image",
            files={"file": ("photo.png", _png_bytes(), "image/png")},
            headers=_auth_headers(customer_token),
        )
        assert resp.status_code == 200, resp.text

    tripped = client.post(
        "/api/v1/uploads/image",
        files={"file": ("photo.png", _png_bytes(), "image/png")},
        headers=_auth_headers(customer_token),
    )
    assert tripped.status_code == 429
    assert "Retry-After" in tripped.headers
