# backend/tests/conftest.py
from typing import AsyncGenerator, Generator

import pytest
from app.core.auth import get_admin_user, get_optional_user
from app.database import Base, get_db

# Import your app and models
from app.main import app
from app import models
from fastapi import Request
from httpx import ASGITransport, AsyncClient
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.pool import StaticPool

# --- DATABASE SETUP ---
# Use in-memory SQLite.
# StaticPool is CRITICAL for in-memory SQLite with async tests to share connection.
SQLALCHEMY_DATABASE_URL = "sqlite:///"
engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    connect_args={"check_same_thread": False},
    poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


@pytest.fixture(scope="session")
def prepare_db():
    Base.metadata.create_all(bind=engine)
    yield
    Base.metadata.drop_all(bind=engine)


@pytest.fixture(scope="function")
def db(prepare_db) -> Generator[Session, None, None]:
    connection = engine.connect()
    transaction = connection.begin()
    session = TestingSessionLocal(bind=connection)
    yield session
    session.close()
    transaction.rollback()
    connection.close()


@pytest.fixture(autouse=True)
def clean_db(db):
    db.query(models.Match).delete()
    db.query(models.Team).delete()
    db.query(models.Court).delete()
    db.commit()
    yield


@pytest.fixture(scope="function")
async def client(db: Session) -> AsyncGenerator[AsyncClient, None]:
    def override_get_db():
        try:
            yield db
        finally:
            pass

    # Strict Auth: Always requires a token (simulated by header presence)
    def override_get_admin_user(request: Request):
        if "Authorization" not in request.headers:
            # Let FastAPI raise the 401 naturally if header is missing
            raise pytest.skip("Auth header missing in strict auth test")
        return "test_admin"

    # Optional Auth: Returns Admin IF header exists, else None
    def override_get_optional_user(request: Request):
        if "Authorization" in request.headers:
            return "test_admin"
        return None

    app.dependency_overrides[get_db] = override_get_db
    app.dependency_overrides[get_admin_user] = override_get_admin_user
    app.dependency_overrides[get_optional_user] = override_get_optional_user

    async with AsyncClient(
        transport=ASGITransport(app=app), base_url="http://test"
    ) as c:
        yield c

    app.dependency_overrides.clear()


# --- HELPER FIXTURES ---


@pytest.fixture
def auth_headers(client):
    return {"Authorization": "Bearer test_token"}


@pytest.fixture
async def valid_tournament_payload(db):
    # 1. Create global courts first
    c1 = models.Court(name="Plan 1")
    c2 = models.Court(name="Plan 2")
    db.add_all([c1, c2])
    db.commit()

    # 2. Return payload with IDs
    return {
        "name": "Test Tournament",
        "code": "1234",
        "type": "Double",
        "timestamp": "2026-05-24T11:00:00",
        "duration": 15,
        "teams": ["Team A", "Team B", "Team C", "Team D"],
        "courts": [c1.id, c2.id],
    }
