import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from app.db import models  # noqa: F401
from app.db.session import Base, get_db
from app.main import app
from app.queue.analysis_queue import reset_analysis_queue_for_tests


@pytest.fixture()
def client():
    reset_analysis_queue_for_tests()
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    Base.metadata.create_all(bind=engine)
    TestingSessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)

    def override_get_db():
        db = TestingSessionLocal()
        try:
            yield db
        finally:
            db.close()

    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as test_client:
        yield test_client
    app.dependency_overrides.clear()
    Base.metadata.drop_all(bind=engine)


@pytest.fixture()
def auth_headers(client):
    resp = client.post(
        "/api/auth/login",
        json={"loginType": "phone_code", "credential": "18600000000", "code": "682139"},
    )
    assert resp.status_code == 200, resp.text
    token = resp.json()["data"]["token"]
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture()
def staff_headers(client, db_session):
    from sqlalchemy import select

    from app.core.security import hash_phone
    from app.db.models import User

    resp = client.post(
        "/api/auth/login",
        json={"loginType": "phone_code", "credential": "18600000001", "code": "682139"},
    )
    assert resp.status_code == 200, resp.text
    token = resp.json()["data"]["token"]
    user = db_session.scalar(select(User).where(User.phone_hash == hash_phone("18600000001")))
    if user:
        user.role = "coach"
        db_session.commit()
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture()
def db_session(client):
    gen = app.dependency_overrides[get_db]()
    db = next(gen)
    try:
        yield db
    finally:
        try:
            next(gen)
        except StopIteration:
            pass
