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

from db.session import get_db
from core.deps import get_current_admin
from domains.groups.schemas import (
    AdminGroupCreate,
    GroupResponse,
    AdminAddMemberRequest,
    GroupMemberResponse
)
from domains.groups.service import (
    create_admin_group,
    list_all_groups_admin,
    add_member_to_group,
    list_group_members_api,
    remove_member_from_group,
    delete_group_service
)

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

@router.post("/", response_model=GroupResponse)
async def admin_create_group(
    payload: AdminGroupCreate,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    """
    Admin always creates public groups and is not auto-added as a member.
    """
    return await create_admin_group(
        db,
        name=payload.name,
        owner_id=admin.id
    )

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

@router.get("/{group_id}/members", response_model=list[GroupMemberResponse])
async def admin_list_members(
    group_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    return await list_group_members_api(db, group_id)

@router.post("/{group_id}/members", response_model=None)
async def force_add_member(
    group_id: uuid.UUID,
    payload: AdminAddMemberRequest,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    """
    Force add a user to a group with a specific role. Bypasses invitation.
    """
    from domains.users.repo import get_user_by_username

    target_user = await get_user_by_username(db, payload.username)
    if not target_user:
        raise HTTPException(status_code=404, detail="User not found")

    try:
        await add_member_to_group(db, group_id, target_user.id, payload.role)
        return {"message": f"User {payload.username} added successfully"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.delete("/{group_id}/members/{user_id}")
async def admin_remove_member(
    group_id: uuid.UUID,
    user_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    """
    Admin can remove any user from any group.
    """
    try:
        await remove_member_from_group(db, group_id, user_id, admin)
        return {"message": "Member removed successfully"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.delete("/{group_id}")
async def admin_delete_group(
    group_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    """
    Admin can delete any group.
    """
    try:
        await delete_group_service(db, group_id, admin)
        return {"message": "Group deleted successfully"}
    except ValueError as e:
        raise HTTPException(status_code=403, detail=str(e))
