from fastapi import APIRouter, Depends, HTTPException, status, Request from sqlalchemy.orm import Session from typing import List, Any 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.services.SystemConfigService import SystemConfigService from app.schemas.SystemConfig import ( CrmLocationCreate, CrmLocationResponse, DeviceTypeCreate, DeviceTypeResponse, UserLocationAssign ) router = APIRouter(prefix="/api/v1/system", tags=["System Infrastructure Configuration"]) def get_system_service(request: Request, db: Session = Depends(get_db)) -> SystemConfigService: tenant_id = getattr(request.state, "tenant_id", "tenant_default") return SystemConfigService(db=db, tenant_id=tenant_id) # --- LOCATIONS ENDPOINTS --- @router.post("/locations", response_model=CrmLocationResponse, status_code=status.HTTP_201_CREATED) def create_location( payload: CrmLocationCreate, svc: SystemConfigService = Depends(get_system_service), current_user: User = Depends(get_current_user) ) -> Any: """Creates a new store or warehouse location.""" return svc.create_location(payload) @router.get("/locations", response_model=List[CrmLocationResponse]) def list_locations( svc: SystemConfigService = Depends(get_system_service) ) -> Any: """Lists all store and warehouse locations.""" return svc.list_locations() @router.get("/system-config/locations", response_model=List[CrmLocationResponse]) def list_locations_alias( svc: SystemConfigService = Depends(get_system_service) ) -> Any: """Compatibility alias for storefront booking wizard.""" return svc.list_locations() # --- DYNAMIC DEVICE TYPES ENDPOINTS --- @router.post("/device-types", response_model=DeviceTypeResponse, status_code=status.HTTP_201_CREATED) def create_device_type( payload: DeviceTypeCreate, svc: SystemConfigService = Depends(get_system_service), current_user: User = Depends(get_current_user) ) -> Any: """Registers a new dynamic device category (Mobile, Tablet, Laptop, Drone, etc.).""" return svc.create_device_type(payload) @router.get("/device-types", response_model=List[DeviceTypeResponse]) def list_device_types( svc: SystemConfigService = Depends(get_system_service), current_user: User = Depends(get_current_user) ) -> Any: """Lists all registered dynamic device categories.""" return svc.list_device_types() # --- USER LOCATION ASSIGNMENT --- @router.post("/user-locations/assign") def assign_user_locations( payload: UserLocationAssign, svc: SystemConfigService = Depends(get_system_service), current_user: User = Depends(get_current_user) ) -> Any: """Assigns location privileges to a staff user with optional Select All Locations toggle.""" assigned_ids = svc.assign_user_locations(payload) return {"message": f"User {payload.user_id} assigned to {len(assigned_ids)} location(s)", "location_ids": assigned_ids}