import pytest
from fastapi.testclient import TestClient

from app.core.database import Base, engine
from app.main import app
from tests._safety_guards import safe_drop_all, safe_rmtree


@pytest.fixture(autouse=True)
def _setup_db():
    """Create tables and seed default users before each test, drop after."""
    Base.metadata.create_all(engine)
    # Trigger startup to seed default users
    with TestClient(app):
        pass
    yield
    safe_drop_all(engine, Base.metadata)


@pytest.fixture()
def client():
    # Codex W2 M3: context manager 패턴으로 lifespan startup/shutdown 확실히 실행.
    with TestClient(app, raise_server_exceptions=False) as c:
        yield c


def test_login_success(client: TestClient):
    resp = client.post("/api/v1/auth/login", json={"username": "admin", "password": "admin123"})
    assert resp.status_code == 200
    data = resp.json()
    assert data["username"] == "admin"
    assert "session" in resp.cookies


def test_login_fail(client: TestClient):
    resp = client.post("/api/v1/auth/login", json={"username": "admin", "password": "wrong"})
    assert resp.status_code == 401


def test_me_without_session(client: TestClient):
    resp = client.get("/api/v1/auth/me")
    assert resp.status_code == 401


def test_me_with_session(client: TestClient):
    login_resp = client.post("/api/v1/auth/login", json={"username": "admin", "password": "admin123"})
    assert login_resp.status_code == 200
    # TestClient automatically carries cookies
    me_resp = client.get("/api/v1/auth/me")
    assert me_resp.status_code == 200
    assert me_resp.json()["role"] == "admin"


def test_logout(client: TestClient):
    client.post("/api/v1/auth/login", json={"username": "admin", "password": "admin123"})
    logout_resp = client.post("/api/v1/auth/logout")
    assert logout_resp.status_code == 200
    me_resp = client.get("/api/v1/auth/me")
    assert me_resp.status_code == 401
