from fastapi import APIRouter, Depends, Request, HTTPException, status
from typing import Optional
from app.db import database
from app.v1.models.saas.rolemodel import Role, RoleCreate, RoleUpdate, RoleListResponse
from app.v1.services.saas.roles import (
    create_role_service,
    list_roles_service,
    get_role_service,
    update_role_service,
    delete_role_service,
)
from app.v1.dependencies.auth import get_current_userdetails

router = APIRouter()

@router.post("/", response_model=Role, tags=["Roles"])
async def create_role(
    role: RoleCreate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    user_role = current_user.get("roles")
    user_account = current_user.get("account_id")
    role.is_system_default = False  
    role.is_global_access = True

    if user_role == 1:
        if role.account_id not in [None, "", user_account]:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Super admin roles must be global."
            )
    elif user_role == 4:
        role.account_id = user_account
    else:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You do not have permission to create roles."
        )

    created_role = create_role_service(role, db)
    return created_role

@router.get("/", response_model=RoleListResponse, tags=["Roles"])
@router.get("/d", response_model=RoleListResponse, tags=["Roles"])
async def list_roles(
    skip: int = 0,
    limit: int = 10,
    search: Optional[str] = None,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails),
    request: Request = None  # <-- added Request dependency

):
    user_role = current_user.get("roles")
    is_saas_only = user_role == 1  # True only for super admin

    if user_role == 1:
        account_id = None
    elif user_role == 4:
        account_id = current_user.get("account_id")
    else:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Insufficient permissions."
        )
    is_system_default = request.url.path.endswith("/d")

    roles_response = list_roles_service(db, skip, limit, account_id, search, is_system_default, is_saas_only)
    return roles_response

@router.get("/{role_id}", response_model=Role, tags=["Roles"])
async def get_role(
    role_id: int,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    role = get_role_service(role_id, db)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Role not found.")

    user_role = current_user.get("roles")
    user_account = current_user.get("account_id")
    if user_role == 1:
        if role.get("account_id") not in [None, "", user_account]:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")
    elif user_role == 4:
        if role.get("account_id") != user_account:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")
    else:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")

    return role

@router.put("/{role_id}", response_model=Role, tags=["Roles"])
async def update_role(
    role_id: int,
    role_update: RoleUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    role = get_role_service(role_id, db)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Role not found.")

    user_role = current_user.get("roles")
    user_account = current_user.get("account_id")
    if user_role == 1:
        if role.get("account_id") not in [None, "", user_account]:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")
    elif user_role == 4:
        if role.get("account_id") != user_account:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")
    else:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")

    updated_role = update_role_service(role_id, role_update, db)
    if not updated_role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Role not found.")
    return updated_role

@router.delete("/{role_id}", response_model=Role, tags=["Roles"])
async def delete_role(
    role_id: int,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    role = get_role_service(role_id, db)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Role not found.")

    user_role = current_user.get("roles")
    user_account = current_user.get("account_id")
    if user_role == 1:
        if role.get("account_id") not in [None, "", user_account]:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")
    elif user_role == 4:
        if role.get("account_id") != user_account:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")
    else:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied.")

    deleted_role = delete_role_service(role_id, db)
    if not deleted_role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Role not found.")
    return deleted_role
