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, get_current_user

from domains.groups.schemas import (
    GroupCreate,
    GroupResponse,
    AddMemberRequest,
    GroupMemberResponse
)

from domains.groups.service import (
    create_new_group,
    list_user_groups,
    list_all_groups_admin,
    list_group_members_api,
    invite_member_to_group,
    remove_member_from_group
)


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


@router.post(
    "/",
    response_model=GroupResponse
)
async def create_group(
    payload: GroupCreate,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    """
    Admin creates Public groups, Regular users create Private groups.
    """
    group = await create_new_group(
        db,
        payload.name,
        user.id,
        user.is_admin
    )

    return group


@router.get("/my", response_model=list[GroupResponse])
async def my_groups(
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    """
    List groups the user is a member of.
    """
    return await list_user_groups(db, user.id)


@router.get("/admin/all", response_model=list[GroupResponse])
async def list_all_groups(
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    """
    Admin can see all groups.
    """
    return await list_all_groups_admin(db)


@router.get("/{group_id}/members", response_model=list[GroupMemberResponse])
async def group_members(
    group_id: str,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    """
    List group members with username and online status.
    """
    return await list_group_members_api(db, group_id)


@router.post("/{group_id}/invite")
async def invite_member(
    group_id: str,
    payload: AddMemberRequest,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    """
    Invite a user by username. Sends a notification.
    """
    try:
        notification = await invite_member_to_group(
            db,
            group_id,
            user.id,
            payload.username
        )
        return {"message": "دعوت ارسال شد", "notification_id": notification.id}
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.delete("/{group_id}/members/{user_id}")
async def remove_member(
    group_id: str,
    user_id: str,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    """
    Admin or Group Manager can remove a member.
    """
    try:
        await remove_member_from_group(
            db,
            group_id,
            user_id,
            user
        )
        return {"message": "عضو با موفقیت حذف شد"}
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=str(e)
        )