def test_login_success(client):
    response = client.post("/api/auth/login", json={"username": "admin", "password": "123456"})

    assert response.status_code == 200
    body = response.json()
    assert body["token"]
    assert body["token_type"] == "bearer"
    assert body["username"] == "admin"
    assert body["user"]["username"] == "admin"


def test_login_rejects_invalid_credentials(client):
    response = client.post("/api/auth/login", json={"username": "admin", "password": "wrong"})

    assert response.status_code == 401
    assert response.json()["detail"] == "Invalid credentials"


def test_me_returns_current_user(client):
    response = client.get("/api/auth/me")

    assert response.status_code == 200
    assert response.json()["username"] == "admin"


def test_business_routes_require_auth(app):
    from fastapi.testclient import TestClient

    with TestClient(app) as unauthenticated:
        response = unauthenticated.get("/api/projects")

    assert response.status_code == 401


def test_default_admin_seed_does_not_claim_legacy_shared_projects(db_session):
    from models import Project
    from routers.auth import ensure_default_admin

    project = Project(name="Legacy Shared Project", owner_user_id=None)
    db_session.add(project)
    db_session.commit()
    db_session.refresh(project)

    ensure_default_admin(db_session)
    db_session.refresh(project)

    assert project.owner_user_id is None


def test_user_model_default_role_is_annotator(db_session):
    from models import User
    from routers.auth import hash_password

    user = User(username="script-created", password_hash=hash_password("secret123"))
    db_session.add(user)
    db_session.commit()
    db_session.refresh(user)

    assert user.role == "annotator"


def test_backend_runtime_defaults_match_current_product():
    from config import settings

    assert settings.sam_default_model == "sam2.1_hiera_tiny"
    assert settings.sam3_external_enabled is False
