"""price_report 表读写。"""
from __future__ import annotations

from datetime import datetime

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.core.rewards import CN_TZ
from app.models.price_report import PriceReport


def create_report(
    db: Session,
    *,
    user_id: int,
    comparison_record_id: int | None,
    store_name: str | None,
    dish_summary: str | None,
    original_platform_id: str | None,
    original_platform_name: str | None,
    original_price_cents: int | None,
    reported_platform_id: str,
    reported_platform_name: str,
    reported_price_cents: int,
    images: list[str],
) -> PriceReport:
    rep = PriceReport(
        user_id=user_id,
        comparison_record_id=comparison_record_id,
        store_name=store_name,
        dish_summary=dish_summary,
        original_platform_id=original_platform_id,
        original_platform_name=original_platform_name,
        original_price_cents=original_price_cents,
        reported_platform_id=reported_platform_id,
        reported_platform_name=reported_platform_name,
        reported_price_cents=reported_price_cents,
        images=images,
        status="pending",
        created_at=datetime.now(CN_TZ).replace(tzinfo=None),  # 存北京 wall-clock(同 savings/comparison)
    )
    db.add(rep)
    db.commit()
    db.refresh(rep)
    return rep


def list_reports(
    db: Session, user_id: int, status: str | None = None
) -> list[PriceReport]:
    """该用户的上报记录,按时间倒序;status 非空时按状态筛选。"""
    stmt = select(PriceReport).where(PriceReport.user_id == user_id)
    if status:
        stmt = stmt.where(PriceReport.status == status)
    stmt = stmt.order_by(PriceReport.created_at.desc(), PriceReport.id.desc())
    return list(db.execute(stmt).scalars().all())
