import os
os.environ["DATABASE_URL"] = "sqlite:///./test_metabloom.db"
os.environ["JWT_SECRET"] = "test-secret-that-is-long-enough-for-tests"

from fastapi.testclient import TestClient
from app.db import Base, engine
from app.main import app


def setup_function():
    Base.metadata.drop_all(engine); Base.metadata.create_all(engine)


def auth(client):
    response = client.post("/auth/register", json={"email": "user@example.com", "password": "a-very-safe-password"})
    assert response.status_code == 201
    return {"Authorization": f"Bearer {response.json()['access_token']}"}


def test_health_auth_crud_export_delete():
    with TestClient(app) as client:
        assert client.get("/health").status_code == 200
        headers = auth(client)
        assert client.post("/entries", headers=headers, json={"kind": "weight", "value": 90, "unit": "kg"}).status_code == 403
        profile = client.put("/profile", headers=headers, json={"display_name": "Alex", "height_cm": 175, "consent_health_data": True})
        assert profile.status_code == 200
        created = client.post("/entries", headers=headers, json={"kind": "weight", "value": 90, "unit": "kg"})
        assert created.status_code == 201
        entry_id = created.json()["id"]
        assert len(client.get("/entries", headers=headers).json()) == 1
        assert client.put(f"/entries/{entry_id}", headers=headers, json={"kind": "weight", "value": 89, "unit": "kg"}).json()["value"] == 89
        assert client.get("/account/export", headers=headers).status_code == 200
        assert client.delete(f"/entries/{entry_id}", headers=headers).status_code == 204
        assert client.delete("/account", headers=headers).status_code == 204


def test_validation_and_isolation():
    with TestClient(app) as client:
        headers = auth(client)
        client.put("/profile", headers=headers, json={"consent_health_data": True})
        assert client.post("/entries", headers=headers, json={"kind": "glucose", "value": 999, "unit": "mg/dL"}).status_code == 422
        assert client.post("/entries", headers=headers, json={"kind": "glucose", "value": 5.5, "unit": "mmol/L"}).status_code == 201
        assert client.post("/entries", headers=headers, json={"kind": "glucose", "value": 5.5, "unit": "mg/dL"}).status_code == 422
        entries = client.get("/entries", headers=headers).json()
        assert len(entries) == 1
        assert entries[0]["unit"] == "mmol/L"
