"""OHLCV router: endpoints for storing and querying price data."""

from datetime import date

from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, require_access
from app.models.user import User
from app.schemas.common import APIEnvelope
from app.schemas.ohlcv import OHLCVCreate, OHLCVResponse
from app.services import price_service

router = APIRouter(tags=["ohlcv"])


@router.post("/ohlcv", response_model=APIEnvelope)
async def create_ohlcv(
    body: OHLCVCreate,
    _user: User = Depends(require_access),
    db: AsyncSession = Depends(get_db),
):
    """Upsert an OHLCV record for a ticker and date."""
    record = await price_service.upsert_ohlcv(
        db,
        symbol=body.symbol,
        record_date=body.date,
        open_=body.open,
        high=body.high,
        low=body.low,
        close=body.close,
        volume=body.volume,
    )
    return APIEnvelope(
        status="success",
        data=OHLCVResponse.model_validate(record).model_dump(mode="json"),
    )


@router.get("/ohlcv/{symbol}", response_model=APIEnvelope)
async def get_ohlcv(
    symbol: str,
    start_date: date | None = Query(None, description="Start date (YYYY-MM-DD)"),
    end_date: date | None = Query(None, description="End date (YYYY-MM-DD)"),
    _user: User = Depends(require_access),
    db: AsyncSession = Depends(get_db),
):
    """Query OHLCV records for a ticker, optionally filtered by date range."""
    records = await price_service.query_ohlcv(db, symbol, start_date, end_date)
    return APIEnvelope(
        status="success",
        data=[
            OHLCVResponse.model_validate(r).model_dump(mode="json")
            for r in records
        ],
    )
