from fastapi import APIRouter, Depends, HTTPException, status

from sqlalchemy.ext.asyncio import AsyncSession

from src.core.errors import AccessDeniedException
from src.api.v1.deps import get_current_active_user, require_admin
from src.db.models.app_user import AppUser
from src.db.session import get_db
from src.domain.schemas import BaseListResponse, BaseSingleResponse, OrgUnitCreateSchema, OrgUnitListSchema, OrgUnitSchema, OrgUnitUpdateSchema, ResponseBase
from src.services.org_unit_service import OrgUnitService



router = APIRouter(prefix="/org-unit", tags=["ssp"])


@router.get("/")
async def org_unit_list(
        offset: int = 0,
        limit: int = 100,
        is_active: bool | None = None,
        is_ssp: bool | None = None,
        load_users_count: bool = False,
        db: AsyncSession = Depends(get_db),
        current_user: AppUser = Depends(require_admin),
) -> BaseListResponse[OrgUnitListSchema]:
    org_service = OrgUnitService(db)
    count, units = await org_service.get_list(
        user=current_user, 
        with_count=True,
        offset=offset,
        limit=limit,
        load_users=load_users_count,
        is_active=is_active,
        is_ssp=is_ssp,

    )
    return BaseListResponse(
        result=[
            OrgUnitListSchema.model_validate(unit) for unit in units
        ],
        count=count,
    )


@router.get("/{org_unit_id}")
async def org_unit_id(
        org_unit_id: int,
        load_users: bool = False,
        db: AsyncSession = Depends(get_db),
        current_user: AppUser = Depends(require_admin),
) -> BaseSingleResponse[OrgUnitSchema]:
    org_service = OrgUnitService(db)
    unit = await org_service.get(
        user=current_user,
        org_unit_id=org_unit_id,
        load_users=load_users,
    )
    if not unit:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="ССП не найден")

    return BaseSingleResponse(
        result = OrgUnitSchema.model_validate(unit)
    )


@router.post("/")
async def create_ssp(
    org_data: OrgUnitCreateSchema,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
) -> BaseSingleResponse[OrgUnitSchema]:
    """Создание ССП/РФ."""
    org_unit_service = OrgUnitService(db)
    org_unit = await org_unit_service.create(
        title=org_data.title, 
        is_ssp=org_data.is_ssp, 
        utc_offset=org_data.utc_offset,
        user=current_user,
    )
    return BaseSingleResponse(
        message="ССП/РФ создана",
        result=OrgUnitSchema.model_validate(org_unit),
    )


@router.patch("/{org_unit_id}")
async def update_ssp(
    org_unit_id: int,
    org_data: OrgUnitUpdateSchema,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
) -> BaseSingleResponse[OrgUnitSchema]:
    """Редактирование ССП/РФ."""
    org_unit_service = OrgUnitService(db)
    org_unit = await org_unit_service.update(
        org_unit_id=org_unit_id,
        user=current_user,
        **org_data.model_dump(exclude_unset=True),
    )
    if not org_unit:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="ССП не найден")

    return BaseSingleResponse(
        message="ССП/РФ обновлена",
        result=OrgUnitSchema.model_validate(org_unit),
    )


@router.delete("/{org_unit_id}")
async def delete_ssp(
    org_unit_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: AppUser = Depends(require_admin),
) -> ResponseBase:
    """Удаление ССП/РФ."""
    org_unit_service = OrgUnitService(db)
    result = await org_unit_service.logical_delete(
        org_unit_id=org_unit_id, 
        user=current_user,
        is_active=True,
    )
    if not result:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="ССП не найден")

    return ResponseBase(success=True, message="ССП/РФ удалена")