from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.orm import Session from sqlalchemy import select from typing import List, Optional from app.core.database.db_session import get_db from app.core.permissions.RoleChecker import get_current_user from app.models.UserModel import User from app.models.WarrantyModel import Warranty from app.schemas.WarrantySchema import WarrantyResponse, WarrantyVoidRequest from app.services.WarrantyService import WarrantyService router = APIRouter(prefix="/api/v1/warranties", tags=["Warranties"]) @router.get("/", response_model=List[WarrantyResponse]) def list_warranties( status: Optional[str] = None, warranty_type: Optional[str] = None, customer_id: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): query = select(Warranty) # Simple tenant isolation for admin vs customer if getattr(current_user, 'role_id', None) == 'ROLE_CUSTOMER': query = query.where(Warranty.customer_id == current_user.user_id) else: # If admin, allow filtering by customer if customer_id: query = query.where(Warranty.customer_id == customer_id) if status: query = query.where(Warranty.status == status) if warranty_type: query = query.where(Warranty.warranty_type == warranty_type) results = db.execute(query).scalars().all() return results @router.post("/{warranty_id}/void", response_model=WarrantyResponse) def void_warranty( warranty_id: str, payload: WarrantyVoidRequest, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): # Only admins can void if getattr(current_user, 'role_id', None) == 'ROLE_CUSTOMER': raise HTTPException(status_code=403, detail="Not authorized to void warranties") return WarrantyService.void_warranty(db, warranty_id, payload.void_reason) @router.post("/{warranty_id}/validate") def validate_warranty_claim( warranty_id: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): # This checks API level validation result = WarrantyService.validate_claim(db, warranty_id) return {"message": "Warranty is valid and claimable", "warranty_id": warranty_id}