"""Tickers router: CRUD endpoints for the Ticker Registry."""

from fastapi import APIRouter, Depends
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.ticker import TickerCreate, TickerResponse
from app.services import ticker_service

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


@router.post("/tickers", response_model=APIEnvelope)
async def create_ticker(
    body: TickerCreate,
    _user: User = Depends(require_access),
    db: AsyncSession = Depends(get_db),
):
    """Add a new ticker to the registry."""
    ticker = await ticker_service.add_ticker(db, body.symbol)
    return APIEnvelope(
        status="success",
        data=TickerResponse.model_validate(ticker).model_dump(mode="json"),
    )


@router.get("/tickers", response_model=APIEnvelope)
async def list_tickers(
    _user: User = Depends(require_access),
    db: AsyncSession = Depends(get_db),
):
    """List all tracked tickers sorted alphabetically."""
    tickers = await ticker_service.list_tickers(db)
    return APIEnvelope(
        status="success",
        data=[
            TickerResponse.model_validate(t).model_dump(mode="json")
            for t in tickers
        ],
    )


@router.delete("/tickers/{symbol}", response_model=APIEnvelope)
async def delete_ticker(
    symbol: str,
    _user: User = Depends(require_access),
    db: AsyncSession = Depends(get_db),
):
    """Delete a ticker and all associated data."""
    await ticker_service.delete_ticker(db, symbol)
    return APIEnvelope(status="success", data=None)
