import datetime
from collections.abc import Iterator

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

from backend.database import Base
from backend.main import app, get_db
from backend.repository import create_news, create_translation


@pytest.fixture
def db_session() -> Iterator[Session]:
    engine = create_engine(
        "sqlite://",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    testing_session_local = sessionmaker(bind=engine, autocommit=False, autoflush=False)
    Base.metadata.create_all(bind=engine)
    session = testing_session_local()
    try:
        yield session
    finally:
        session.close()


@pytest.fixture
def client(db_session: Session) -> Iterator[TestClient]:
    def override_get_db() -> Iterator[Session]:
        try:
            yield db_session
        finally:
            pass

    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as test_client:
        yield test_client
    app.dependency_overrides.clear()


@pytest.fixture
def seeded_news(db_session: Session) -> int:
    now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
    item = create_news(
        db=db_session,
        headline="Market rally follows AI earnings beat",
        summary="Major indices rose after strong AI-focused earnings results.",
        source_url="https://example.com/market-rally",
        image_url="/static/images/placeholder.png",
        image_credit="Example",
        tldr_points=["Markets rose", "AI earnings strong", "Investors optimistic"],
        summary_body="A broad market rally followed stronger-than-expected AI earnings.",
        source_citation="Example source",
        summary_image_url="/static/images/placeholder.png",
        summary_image_credit="Example",
        published_at=now,
    )
    create_translation(
        db=db_session,
        news_item_id=item.id,
        language="ta",
        headline="ஏஐ வருமானத்துக்கு பின் சந்தை உயர்வு",
        summary="ஏஐ சார்ந்த வருமானம் உயர்வைத் தொடர்ந்து சந்தை முன்னேறியது.",
    )
    return item.id
