"""Tests for user cabinet endpoints."""
import pytest
from httpx import AsyncClient

from app.models.drug import Drug

DEVICE_HEADER = {"X-Device-ID": "test-device-uuid-12345678"}


@pytest.mark.asyncio
async def test_cabinet_empty(client: AsyncClient):
    response = await client.get("/api/v1/cabinet", headers=DEVICE_HEADER)
    assert response.status_code == 200
    data = response.json()
    assert data["total"] == 0
    assert data["items"] == []


@pytest.mark.asyncio
async def test_add_to_cabinet(client: AsyncClient, sample_drugs: list[Drug]):
    drug = sample_drugs[0]
    response = await client.post(
        "/api/v1/cabinet",
        headers=DEVICE_HEADER,
        json={"item_type": "drug", "item_id": drug.id},
    )
    assert response.status_code == 201
    data = response.json()
    assert data["item_type"] == "drug"
    assert data["item_id"] == drug.id
    assert data["device_id"] == "test-device-uuid-12345678"


@pytest.mark.asyncio
async def test_add_duplicate_rejected(client: AsyncClient, sample_drugs: list[Drug]):
    drug = sample_drugs[0]
    payload = {"item_type": "drug", "item_id": drug.id}
    await client.post("/api/v1/cabinet", headers=DEVICE_HEADER, json=payload)
    response = await client.post("/api/v1/cabinet", headers=DEVICE_HEADER, json=payload)
    assert response.status_code == 409


@pytest.mark.asyncio
async def test_remove_from_cabinet(client: AsyncClient, sample_drugs: list[Drug]):
    drug = sample_drugs[0]
    create_resp = await client.post(
        "/api/v1/cabinet",
        headers=DEVICE_HEADER,
        json={"item_type": "drug", "item_id": drug.id},
    )
    cabinet_id = create_resp.json()["id"]

    response = await client.delete(f"/api/v1/cabinet/{cabinet_id}", headers=DEVICE_HEADER)
    assert response.status_code == 204


@pytest.mark.asyncio
async def test_remove_nonexistent_returns_404(client: AsyncClient):
    response = await client.delete("/api/v1/cabinet/99999", headers=DEVICE_HEADER)
    assert response.status_code == 404


@pytest.mark.asyncio
async def test_cabinet_requires_device_id(client: AsyncClient):
    response = await client.get("/api/v1/cabinet")
    assert response.status_code == 401


@pytest.mark.asyncio
async def test_cabinet_invalid_item_type(client: AsyncClient):
    response = await client.post(
        "/api/v1/cabinet",
        headers=DEVICE_HEADER,
        json={"item_type": "invalid", "item_id": 1},
    )
    assert response.status_code == 422
