import asyncio
from collections.abc import AsyncGenerator
from uuid import uuid4

import pytest
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from src.infrastructure.database.models import Base
from src.main import app


TEST_DATABASE_URL = "postgresql+asyncpg://pip:pip-secret@localhost:5432/pip_test"


@pytest.fixture(scope="session")
def event_loop():
    loop = asyncio.new_event_loop()
    yield loop
    loop.close()


@pytest_asyncio.fixture(scope="session")
async def test_engine():
    engine = create_async_engine(TEST_DATABASE_URL, echo=False)
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield engine
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await engine.dispose()


@pytest_asyncio.fixture
async def db_session(test_engine) -> AsyncGenerator[AsyncSession, None]:
    session_factory = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
    async with session_factory() as session:
        yield session
        await session.rollback()


@pytest_asyncio.fixture
async def client(db_session: AsyncSession) -> AsyncGenerator[AsyncClient, None]:
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        yield c


@pytest.fixture
def sample_pharmacy_data():
    return {
        "code": f"PHARM-{uuid4().hex[:8]}",
        "name": "Test Pharmacy",
        "address": "Calle Test 123",
        "city": "Madrid",
        "province": "Madrid",
        "postal_code": "28001",
        "country": "ES",
        "latitude": 40.4168,
        "longitude": -3.7038,
        "phone": "+34912345678",
        "email": "test@pharmacy.es",
        "erp_type": "farmatic",
        "sync_strategy": "incremental",
        "sync_interval_minutes": 30,
    }


@pytest.fixture
def sample_user_data():
    return {
        "username": f"testuser_{uuid4().hex[:8]}",
        "password": "TestPass123!",
        "email": "test@pip.es",
        "full_name": "Test User",
        "role": "viewer",
    }
