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_user
from domains.groups.schemas import (
    GroupCreate,
    GroupResponse,
    AddMemberRequest,
    GroupMemberResponse,
)
from domains.groups.service import (
    create_user_group,
    list_user_groups,
    list_group_members_api,
    invite_member_to_group,
    delete_group_service,
    remove_member_from_group
)

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

@router.post("/", response_model=GroupResponse)
async def user_create_group(
    payload: GroupCreate,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    """
    Regular users always create private groups and become the first manager.
    """
    return await create_user_group(
        db,
        name=payload.name,
        owner_id=user.id
    )

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

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

@router.post("/{group_id}/invite")
async def invite_member(
    group_id: uuid.UUID,
    payload: AddMemberRequest,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    try:
        notification = await invite_member_to_group(
            db,
            group_id,
            user.id,
            payload.username
        )
        return {"message": "Invitation sent", "notification_id": str(notification.id)}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.delete("/{group_id}")
async def delete_my_group(
    group_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    """
    Only the Group Owner (creator) can delete the group.
    """
    try:
        await delete_group_service(db, group_id, user)
        return {"message": "Group deleted successfully"}
    except ValueError as e:
        raise HTTPException(status_code=403, detail=str(e))
    
@router.delete("/{group_id}/members/{user_id}")
async def remove_member(
    group_id: uuid.UUID,
    user_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    """
    A group manager can remove members from their own group.
    """
    try:
        await remove_member_from_group(db, group_id, user_id, user)
        return {"message": "Member removed successfully"}
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
