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

from db.session import get_db
from core.deps import get_current_admin

from domains.admin.schemas import (
    AdminCreateUser,
    AdminCreateUserResult,
    AdminResetSecretResult,
    AdminUserResponse
)

from domains.admin.service import (
    admin_create_user,
    admin_reset_user_secret
)
from domains.users.repo import get_all_users

from domains.notifications.schemas import NotificationResponse
from domains.notifications.repo import get_all_notifications


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


@router.post("/users", response_model=AdminCreateUserResult)
async def create_user(
    payload: AdminCreateUser,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):

    try:
        user, secret = await admin_create_user(
            db,
            payload.username,
            payload.phone_number
        )

    except ValueError as e:

        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )

    return {
        "user": user,
        "secret": secret
    }


@router.post("/users/{user_id}/logout")
async def logout_user(
    user_id: str,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    from domains.admin.service import admin_logout_user
    user = await admin_logout_user(db, user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="نام‌ کاربری یافت نشد"
        )
    return {"message": "خروج کاربر با موفقیت انجام شد"}


@router.post("/users/{user_id}/reset-secret",
             response_model=AdminResetSecretResult)
async def reset_secret(
    user_id: str,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):

    new_secret = await admin_reset_user_secret(
        db,
        user_id
    )

    if not new_secret:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="نام کاربری یافت نشد"
        )

    return {"secret": new_secret}

@router.get("/users", response_model=list[AdminUserResponse])
async def list_users(
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    return await get_all_users(db, include_admin=True)


    return await get_all_users(db, include_admin=True)


@router.get("/notifications", response_model=list[NotificationResponse])
async def list_notifications(
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    return await get_all_notifications(db)
