from fastapi import APIRouter, HTTPException, status, Depends
from app.schemas import MessageCreate, MessageResponse, ConversationResponse
from app.services.chat_service import ChatService
from app.auth import get_current_user

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

@router.get("/conversations", response_model=list)
def get_conversations(current_user: dict = Depends(get_current_user)):
    """Get all conversations for current user"""
    return ChatService.get_conversations(current_user["user_id"])

@router.get("/conversations/{conversation_id}/messages", response_model=list)
def get_messages(
    conversation_id: int,
    limit: int = 50,
    current_user: dict = Depends(get_current_user)
):
    """Get messages from a conversation"""
    try:
        return ChatService.get_messages(current_user["user_id"], conversation_id, limit)
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=str(e)
        )

@router.post("/conversations/{conversation_id}/messages", response_model=MessageResponse)
def send_message(
    conversation_id: int,
    message_data: MessageCreate,
    current_user: dict = Depends(get_current_user)
):
    """Send a message in a conversation"""
    try:
        return ChatService.send_message(
            current_user["user_id"],
            conversation_id,
            message_data.content
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=str(e)
        )

@router.post("/conversations/{conversation_id}/mark-read")
def mark_messages_as_read(
    conversation_id: int,
    current_user: dict = Depends(get_current_user)
):
    """Mark all unread messages in a conversation as read"""
    try:
        return ChatService.mark_messages_as_read(current_user["user_id"], conversation_id)
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=str(e)
        )
