# 操作路由
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.auth import get_current_user
from app.models.models import User, Collection, Operation
from app.schemas.schemas import OperationCreate, OperationResponse

router = APIRouter(prefix="/api", tags=["操作"])


@router.get("/operations", response_model=List[OperationResponse])
def get_operations(
    collection_id: Optional[str] = None,
    page: int = Query(1, ge=1),
    limit: int = Query(50, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取操作历史"""
    query = db.query(Operation).filter(Operation.user_id == current_user.id)
    
    if collection_id:
        query = query.filter(Operation.collection_id == collection_id)
    
    operations = query.order_by(Operation.created_at.desc()) \
        .offset((page - 1) * limit) \
        .limit(limit) \
        .all()
    
    return operations


@router.get("/operations/history")
def get_operation_history(
    collection_id: Optional[str] = None,
    type: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    page: int = Query(1, ge=1),
    limit: int = Query(50, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取操作历史（带统计）"""
    query = db.query(Operation).filter(Operation.user_id == current_user.id)
    
    if collection_id:
        query = query.filter(Operation.collection_id == collection_id)
    if type:
        query = query.filter(Operation.type == type)
    if start_date:
        query = query.filter(Operation.created_at >= start_date)
    if end_date:
        query = query.filter(Operation.created_at <= end_date)
    
    total = query.count()
    
    data = query.order_by(Operation.created_at.desc()) \
        .offset((page - 1) * limit) \
        .limit(limit) \
        .all()
    
    return {
        "data": data,
        "pagination": {
            "page": page,
            "limit": limit,
            "total": total,
            "pages": (total + limit - 1) // limit
        }
    }


@router.post("/operations", response_model=OperationResponse)
def create_operation(
    operation_data: OperationCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建操作记录"""
    # 验证藏品存在
    collection = db.query(Collection).filter(
        Collection.id == operation_data.collection_id,
        Collection.user_id == current_user.id
    ).first()
    
    if not collection:
        raise HTTPException(status_code=404, detail="藏品不存在")
    
    operation = Operation(
        collection_id=operation_data.collection_id,
        user_id=current_user.id,
        type=operation_data.type,
        price=operation_data.price,
        note=operation_data.note
    )
    
    db.add(operation)
    db.commit()
    db.refresh(operation)
    
    return operation
