"""feedback 表读写。"""
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.feedback import Feedback


def create_feedback(
    db: Session,
    *,
    user_id: int,
    content: str,
    contact: str,
    images: list[str] | None,
    source: str = "profile",
    scene: str | None = None,
    app_version: str | None = None,
    device_model: str | None = None,
    rom_name: str | None = None,
    android_version: str | None = None,
) -> Feedback:
    fb = Feedback(
        user_id=user_id,
        content=content,
        contact=contact,
        source=source,
        scene=scene or None,
        images=images or None,
        app_version=app_version or None,
        device_model=device_model or None,
        rom_name=rom_name or None,
        android_version=android_version or None,
        status="pending",
        created_at=datetime.now(CN_TZ).replace(tzinfo=None),
    )
    db.add(fb)
    db.commit()
    db.refresh(fb)
    return fb


def list_feedback(db: Session, *, user_id: int) -> list[Feedback]:
    stmt = (
        select(Feedback)
        .where(Feedback.user_id == user_id)
        .order_by(Feedback.created_at.desc(), Feedback.id.desc())
    )
    return list(db.execute(stmt).scalars().all())
