from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from src.api.v1.deps import (
    get_current_active_user,
    require_admin,
    require_executor_dfip,
)
from src.db.session import get_db
from src.db.models.app_user import AppUser
from src.domain.schemas import BaseListResponse, BaseSingleResponse, User as UserSchema, UserAdminListResponse
from src.domain.schemas import (
    SSPIDList,
    ResponseBase,
    UserCreate,
    UserListResponse,
    UserResponse,
    UserSSPLinkBase,
    UserSSPLinkResponse,
    UserUpdate,
)
from src.services.user_service import UserService

router = APIRouter(prefix="/users", tags=["users"])


@router.get("/me", response_model=UserAdminListResponse)
async def get_current_user_info(
    current_user: AppUser = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db),
    load_orgs: bool = False,
):
    if load_orgs:
        user_service = UserService(db)
        result = await user_service.get(user_id=current_user.id, load_orgs=True)
        return UserAdminListResponse.model_validate(result)
    else:
        return current_user


@router.get("/")
async def get_users(
    skip: int = 0,
    limit: int = 100,
    load_orgs: bool = False,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
) -> BaseListResponse[UserAdminListResponse]:
    user_service = UserService(db)
    count, users = await user_service.get_all(
        current_user, 
        skip=skip, 
        limit=limit, 
        load_orgs=load_orgs,
        with_count=True
    )

    return BaseListResponse(
        count=count,
        result=[UserAdminListResponse.model_validate(user) for user in users]
    )


@router.get("/dfip-many-ssp/", response_model=UserSSPLinkResponse)
async def get_many_ssp(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_executor_dfip),
):
    user_service = UserService(db)
    ssp_list = await user_service.get_many_ssp(user_id, current_user)
    return UserSSPLinkResponse(
        success=True,
        message="OK",
        result=UserSSPLinkBase(user_id=user_id, ssp=ssp_list),
    )


@router.put("/dfip-many-ssp/", response_model=ResponseBase)
async def set_many_ssp(
    user_id: int,
    ssp_ids_data: SSPIDList,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
):
    user_service = UserService(db)
    success = await user_service.set_many_ssp(user_id, ssp_ids_data.ssp_ids, current_user)
    return ResponseBase(
        success=success,
        message="OK" if success else "Ошибка при прикреплении ССП/РФ",
    )


@router.delete("/dfip-many-ssp/", response_model=ResponseBase)
async def unset_many_ssp(
    user_id: int,
    ssp_ids_data: SSPIDList,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
):
    user_service = UserService(db)
    success = await user_service.unset_many_ssp(
        user_id, ssp_ids_data.ssp_ids, current_user
    )
    return ResponseBase(
        success=success,
        message="OK" if success else "Ошибка при откреплении ССП/РФ",
    )


@router.get("/{user_id}")
async def get_user(
    user_id: int,
    load_orgs: bool = False,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
) -> UserAdminListResponse:
    user_service = UserService(db)
    user = await user_service.get(
        user_id=user_id, 
        current_user=current_user,
        load_orgs=load_orgs,
    )
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Пользователь не найден",
        )
    return UserAdminListResponse.model_validate(user)



@router.post("/", response_model=BaseSingleResponse[UserAdminListResponse])
async def create_user(
    user_data: UserCreate,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
):
    user_service = UserService(db)
    user = await user_service.create_user(user_data=user_data, creator=current_user)

    result = UserAdminListResponse.model_validate(user)
    if user_data.load_orgs:
        result.org_units = []

    return BaseSingleResponse(success=True, message="Пользователь создан", result=result)


@router.patch("/{user_id}", response_model=BaseSingleResponse[UserAdminListResponse])
async def update_user(
    user_id: int,
    user_data: UserUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
):
    user_service = UserService(db)
    user = await user_service.update_user(
        user_id=user_id,
        user_data=user_data,
        user=current_user,
    )
    result = UserAdminListResponse.model_validate(user)
    return UserResponse(success=True, message="Пользователь обновлен", result=result)


@router.delete("/{user_id}", response_model=UserResponse)
async def delete_user(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
):
    user_service = UserService(db)
    await user_service.delete_user(user_id=user_id, user=current_user)
    return UserResponse(success=True, message="Пользователь удалён")
 