"""Integration test: sync jobs (FRED/FINRA → DB rows)."""

import datetime as dt

import pytest


@pytest.mark.integration
@pytest.mark.asyncio
async def test_macro_series_insert(db_session, fred_observations_fixture):
    """FRED sync should create macro_series + macro_observations rows."""
    from sqlalchemy import select

    from libs.db.models import MacroObservation, MacroSeries

    # Upsert macro_series
    series = MacroSeries(
        series_id="DGS10",
        title="10-Year Treasury",
        frequency="daily",
        source_name="fred",
    )
    db_session.add(series)
    await db_session.flush()

    # Insert observations
    for obs in fred_observations_fixture["data"]["observations"]:
        ob = MacroObservation(
            series_id="DGS10",
            observation_date=dt.date.fromisoformat(obs["date"]),
            value=obs["value"],
        )
        db_session.add(ob)
    await db_session.flush()

    result = await db_session.execute(
        select(MacroObservation).where(MacroObservation.series_id == "DGS10")
    )
    rows = result.scalars().all()
    assert len(rows) == 4


@pytest.mark.integration
@pytest.mark.asyncio
async def test_short_sale_daily_insert(db_session, short_volume_fixture):
    """FINRA sync should create short_sale_daily rows."""
    from sqlalchemy import select

    from libs.db.models import ShortSaleDaily

    for entry in short_volume_fixture["entries"]:
        row = ShortSaleDaily(
            ticker_raw="AAPL",
            trade_date=dt.date.fromisoformat(entry["date"]),
            short_volume=entry["short_volume"],
            short_exempt_volume=entry.get("short_exempt_volume"),
            total_volume=entry.get("total_volume"),
            source_name="finra",
        )
        db_session.add(row)
    await db_session.flush()

    result = await db_session.execute(
        select(ShortSaleDaily).where(ShortSaleDaily.ticker_raw == "AAPL")
    )
    rows = result.scalars().all()
    assert len(rows) == 3
