from typing import List

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session

from app.core.usecases.auth_service import verify_token
from app.infrastructure.database.dependencies import get_db
from app.core.entities.role import RoleEntity
from app.core.usecases.role_service import RolesService
from app.infrastructure.database.models.users import User

router = APIRouter()


@router.get("/roles", response_model=List[RoleEntity])
def read_roles(db: Session = Depends(get_db),
               current_user: User = Depends(verify_token)):
    service = RolesService(db)
    return service.get_all_roles()


@router.get("/roles/{role_id}", response_model=RoleEntity)
def read_role(role_id: int, db: Session = Depends(get_db),
              current_user: User = Depends(verify_token)):
    service = RolesService(db)
    role = service.get_role_by_id(role_id)
    if role is None:
        raise HTTPException(status_code=404, detail="Role not found")
    return role


@router.post("/roles", response_model=RoleEntity)
def create_role(role: RoleEntity, db: Session = Depends(get_db),
                current_user: User = Depends(verify_token)):
    service = RolesService(db)
    return service.create_role(role)


@router.put("/roles/{role_id}", response_model=RoleEntity)
def update_role(role_id: int, role: RoleEntity, db: Session = Depends(get_db),
                current_user: User = Depends(verify_token)):
    service = RolesService(db)
    updated_role = service.update_role(role_id, role)
    if updated_role is None:
        raise HTTPException(status_code=404, detail="Role not found")
    return updated_role


@router.delete("/roles/{role_id}", response_model=bool)
def delete_role(role_id: int, db: Session = Depends(get_db),
                current_user: User = Depends(verify_token)):
    service = RolesService(db)
    success = service.delete_role(role_id)
    if not success:
        raise HTTPException(status_code=404, detail="Role not found")
    return success
