from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session
from typing import Optional, List
from utils.utils import get_db
from . import handler
from .schema import TransactionCreate, TransactionUpdate, TransactionResponse, TransactionTypeEnum, TransactionStatusEnum

router = APIRouter(prefix="/transactions", tags=["Transactions"])


@router.post(
    "/",
    response_model=TransactionResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Create Transaction",
    description="Creates a new transaction record for platform fees, seller payouts, refunds, or other financial activities. Validates that the referenced user and optional order exist. Returns 400 if user or order is not found.",
)
def create_transaction_route(data: TransactionCreate, db: Session = Depends(get_db)):
    return handler.create_transaction(db, data)


@router.get(
    "/{id}",
    response_model=TransactionResponse,
    summary="Get Transaction By ID",
    description="Retrieves a single transaction by its unique identifier. Returns 404 if the transaction does not exist.",
)
def get_transaction_route(id: str, db: Session = Depends(get_db)):
    return handler.get_transaction(db, id)


@router.get(
    "/",
    response_model=List[TransactionResponse],
    summary="List Transactions",
    description="Returns a paginated list of transactions. Supports optional filtering by user_id, order_id, transaction_type, and status. Results are ordered by creation date descending.",
)
def list_transactions_route(
    limit: int = Query(20, ge=1, le=100),
    offset: int = Query(0, ge=0),
    user_id: Optional[str] = None,
    order_id: Optional[str] = None,
    transaction_type: Optional[TransactionTypeEnum] = Query(None),
    status: Optional[TransactionStatusEnum] = Query(None),
    db: Session = Depends(get_db),
):
    return handler.list_transactions(
        db,
        limit,
        offset,
        user_id=user_id,
        order_id=order_id,
        transaction_type=transaction_type.value if transaction_type else None,
        status=status.value if status else None,
    )


@router.put(
    "/{id}",
    response_model=TransactionResponse,
    summary="Update Transaction",
    description="Updates an existing transaction. Only provided fields are updated; unset fields remain unchanged. Validates that any new user_id or order_id references exist. Returns 404 if transaction not found, 400 if referenced entities are invalid.",
)
def update_transaction_route(id: str, data: TransactionUpdate, db: Session = Depends(get_db)):
    return handler.update_transaction(db, id, data)


@router.delete(
    "/{id}",
    status_code=status.HTTP_200_OK,
    summary="Delete Transaction",
    description="Permanently deletes a transaction record. Returns 404 if the transaction does not exist.",
)
def delete_transaction_route(id: str, db: Session = Depends(get_db)):
    return handler.delete_transaction(db, id)