from sqlalchemy.orm import Session from fastapi import HTTPException, status, BackgroundTasks from typing import List, Optional import uuid from app.models.auth.user_model import User from app.schemas.auth.user_schema import UserCreate, UserUpdate from app.services.auth.user_service import UserService class UserController: @staticmethod def _resolve_tenant_id(current_user: User, requested_tenant_id: Optional[uuid.UUID]) -> Optional[uuid.UUID]: if current_user.tenant_id is None: return requested_tenant_id if requested_tenant_id and requested_tenant_id != current_user.tenant_id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized to access this tenant" ) return current_user.tenant_id @staticmethod def create_user(db: Session, user_data: UserCreate, current_user: User, background_tasks: BackgroundTasks) -> User: tenant_id = UserController._resolve_tenant_id(current_user, user_data.tenant_id) return UserService.create_user(db, user_data, tenant_id, background_tasks) @staticmethod def get_all_users(db: Session, current_user: User) -> List[User]: tenant_id = current_user.tenant_id return UserService.get_all_users(db, tenant_id) @staticmethod def get_user_by_id(db: Session, user_id: uuid.UUID, current_user: User) -> User: tenant_id = current_user.tenant_id return UserService.get_user_by_id(db, user_id, tenant_id) @staticmethod def update_user(db: Session, user_id: uuid.UUID, user_data: UserUpdate, current_user: User, background_tasks: BackgroundTasks) -> User: if current_user.tenant_id is not None and user_data.tenant_id is not None: UserController._resolve_tenant_id(current_user, user_data.tenant_id) tenant_id = current_user.tenant_id return UserService.update_user(db, user_id, user_data, tenant_id, background_tasks) @staticmethod def delete_user(db: Session, user_id: uuid.UUID, current_user: User): tenant_id = current_user.tenant_id return UserService.delete_user(db, user_id, tenant_id) @staticmethod def get_users_paginated( db: Session, current_user: User, page: int = 1, page_size: int = 10, search: Optional[str] = None, status: Optional[str] = None, ): tenant_id = current_user.tenant_id return UserService.get_users_paginated( db=db, tenant_id=tenant_id, page=page, page_size=page_size, search=search, status=status, )