"""Dashboard query helpers."""

from datetime import datetime
from typing import Optional

from sqlalchemy.orm import Session

from ..repositories import checkout_sessions as session_repo


def parse_date(value: Optional[str]) -> Optional[datetime]:
    if not value:
        return None
    try:
        return datetime.fromisoformat(value)
    except ValueError:
        return None


def list_sessions(
    db: Session,
    partner_id: str,
    q: Optional[str],
    status: Optional[str],
    payout_status: Optional[str],
    date_from: Optional[str],
    date_to: Optional[str],
):
    return session_repo.list_sessions_filtered(
        db,
        partner_id,
        q,
        status,
        payout_status,
        parse_date(date_from),
        parse_date(date_to),
    )


def totals(db: Session, partner_id: str):
    return session_repo.get_totals(db, partner_id)
