"""
Tests that write endpoints require authentication (US2).
These use the authed_client fixture which wires JWTAuthProvider.
"""
import io

import pytest


def _minimal_jpeg() -> bytes:
    return (
        b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x02"
        b"\xff\xd9"
    )


@pytest.mark.asyncio
async def test_upload_without_token_returns_401(authed_client):
    client, _ = authed_client
    data = _minimal_jpeg()
    response = await client.post(
        "/api/v1/images",
        files={"file": ("test.jpg", io.BytesIO(data), "image/jpeg")},
    )
    assert response.status_code == 401
    assert response.json().get("code") == "unauthorized"


@pytest.mark.asyncio
async def test_upload_with_valid_token_succeeds(authed_client):
    client, token = authed_client
    data = _minimal_jpeg()
    response = await client.post(
        "/api/v1/images",
        files={"file": ("test.jpg", io.BytesIO(data), "image/jpeg")},
        headers={"Authorization": f"Bearer {token}"},
    )
    assert response.status_code in (200, 201)


@pytest.mark.asyncio
async def test_delete_without_token_returns_401(authed_client):
    client, _ = authed_client
    response = await client.delete("/api/v1/i/NotFound")
    assert response.status_code == 401
    assert response.json().get("code") == "unauthorized"


@pytest.mark.asyncio
async def test_delete_with_valid_token_succeeds(authed_client):
    client, token = authed_client
    data = _minimal_jpeg()
    upload = await client.post(
        "/api/v1/images",
        files={"file": ("del-protected.jpg", io.BytesIO(data), "image/jpeg")},
        headers={"Authorization": f"Bearer {token}"},
    )
    image_id = upload.json()["short_id"]
    response = await client.delete(
        f"/api/v1/i/{image_id}",
        headers={"Authorization": f"Bearer {token}"},
    )
    assert response.status_code == 204


@pytest.mark.asyncio
async def test_patch_tags_without_token_returns_401(authed_client):
    client, _ = authed_client
    response = await client.patch(
        "/api/v1/i/NotFound/tags",
        json={"tags": ["a"]},
    )
    assert response.status_code == 401
    assert response.json().get("code") == "unauthorized"


@pytest.mark.asyncio
async def test_patch_tags_with_valid_token_succeeds(authed_client):
    client, token = authed_client
    data = _minimal_jpeg()
    upload = await client.post(
        "/api/v1/images",
        files={"file": ("tag-protected.jpg", io.BytesIO(data), "image/jpeg")},
        headers={"Authorization": f"Bearer {token}"},
    )
    image_id = upload.json()["short_id"]
    response = await client.patch(
        f"/api/v1/i/{image_id}/tags",
        json={"tags": ["protected-tag"]},
        headers={"Authorization": f"Bearer {token}"},
    )
    assert response.status_code == 200
