from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from typing import List from ..database import get_db from ..models import ForwardingRule, Account from ..schemas import RuleCreate, RuleUpdate, RuleOut router = APIRouter(prefix="/rules", tags=["rules"]) @router.get("/", response_model=List[RuleOut]) def list_rules(account_id: int | None = None, db: Session = Depends(get_db)): q = db.query(ForwardingRule) if account_id is not None: q = q.filter(ForwardingRule.account_id == account_id) return q.all() @router.post("/", response_model=RuleOut, status_code=201) def create_rule(payload: RuleCreate, db: Session = Depends(get_db)): if not db.get(Account, payload.account_id): raise HTTPException(status_code=404, detail="Account not found") obj = ForwardingRule(**payload.model_dump()) db.add(obj) db.commit() db.refresh(obj) return obj @router.get("/{rule_id}", response_model=RuleOut) def get_rule(rule_id: int, db: Session = Depends(get_db)): obj = db.get(ForwardingRule, rule_id) if not obj: raise HTTPException(status_code=404, detail="Rule not found") return obj @router.patch("/{rule_id}", response_model=RuleOut) def update_rule(rule_id: int, payload: RuleUpdate, db: Session = Depends(get_db)): obj = db.get(ForwardingRule, rule_id) if not obj: raise HTTPException(status_code=404, detail="Rule not found") for field, value in payload.model_dump(exclude_unset=True).items(): setattr(obj, field, value) db.commit() db.refresh(obj) return obj @router.delete("/{rule_id}", status_code=204) def delete_rule(rule_id: int, db: Session = Depends(get_db)): obj = db.get(ForwardingRule, rule_id) if not obj: raise HTTPException(status_code=404, detail="Rule not found") db.delete(obj) db.commit()