"""Agency CRUD endpoints.""" from __future__ import annotations from typing import Optional from fastapi import APIRouter, Depends, Query from app.middleware.auth import get_current_user, require_admin, require_agency_or_admin from app.schemas.agency import ( AgencyCreate, AgencyListResponse, AgencyResponse, AgencyUpdate, ) from app.services.agency_service import AgencyService router = APIRouter(prefix="/agencies", tags=["Agencies"]) @router.get("/", response_model=AgencyListResponse) def list_agencies( page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), verified_only: bool = Query(False), ): svc = AgencyService() return svc.list_agencies(page=page, page_size=page_size, verified_only=verified_only) @router.get("/me", response_model=AgencyResponse) def get_my_agency(user: dict = Depends(get_current_user)): svc = AgencyService() return svc.get_agency_by_user(user["id"]) @router.get("/{agency_id}", response_model=AgencyResponse) def get_agency(agency_id: str): svc = AgencyService() return svc.get_agency(agency_id) @router.post("/", response_model=AgencyResponse, status_code=201) def create_agency(body: AgencyCreate, user: dict = Depends(get_current_user)): svc = AgencyService() # Prevent duplicate agencies for the same user try: existing = svc.get_agency_by_user(user["id"]) return existing except Exception: pass return svc.create_agency(user["id"], body.model_dump()) @router.patch("/{agency_id}", response_model=AgencyResponse) def update_agency( agency_id: str, body: AgencyUpdate, user: dict = Depends(get_current_user), ): svc = AgencyService() return svc.update_agency( agency_id, user["id"], user["role"], body.model_dump(exclude_unset=True) ) @router.post("/{agency_id}/verify", response_model=AgencyResponse) def verify_agency(agency_id: str, admin: dict = Depends(require_admin)): svc = AgencyService() return svc.verify_agency(agency_id, admin["role"]) @router.post("/{agency_id}/revoke", response_model=AgencyResponse) def revoke_agency_verification(agency_id: str, admin: dict = Depends(require_admin)): svc = AgencyService() return svc.revoke_verification(agency_id, admin["role"]) @router.delete("/{agency_id}") def delete_agency(agency_id: str, _admin: dict = Depends(require_admin)): svc = AgencyService() return svc.delete_agency(agency_id)