# app/api/v1/endpoints/messages.py
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import func, case
from app.api import deps
from app.schemas.message import MessageCreate, MessageResponse
from app.models.message import Message
from app.services import message_service

router = APIRouter()

@router.post("/", response_model=MessageResponse)
def send_message(
    payload: MessageCreate,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Allows the currently logged-in user to send a new message.
    The sender_id is derived from the authenticated user's ID,
    and the message is saved based on the receiver_id and content from the payload.
    """
    message = message_service.create_message(db, current_user.id, payload.receiver_id, payload.content)
    return message

@router.get("/", response_model=List[MessageResponse])
def get_messages(
    friend_id: int,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Retrieves the conversation history between the current user and a friend.
    """
    messages = message_service.get_messages_between_users(db, current_user.id, friend_id)
    if not messages:
        raise HTTPException(status_code=404, detail="No conversation found")
    return messages

@router.get("/unread", response_model=List[MessageResponse])
def get_unread_messages(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Retrieves all unread messages for the current logged-in user.
    """
    unread = message_service.get_unread_messages(db, receiver_id=current_user.id)
    return unread

@router.get("/threads", response_model=List[MessageResponse])
def get_conversation_threads(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    로그인한 사용자가 참여하는 모든 대화 스레드를 조회합니다.
    각 스레드는 해당 대화 상대(친구)와의 최신 메시지를 포함합니다.
    """
    threads = message_service.get_conversation_threads(db, current_user.id)
    if not threads:
        raise HTTPException(status_code=404, detail="No conversations found.")
    return threads

@router.get("/conversation/{friend_id}", response_model=List[MessageResponse])
def get_conversation_with_user(
    friend_id: int,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Retrieves the full conversation history between the current user and the specified friend.
    """
    messages = message_service.get_messages_between_users(db, current_user.id, friend_id)
    if not messages:
        raise HTTPException(status_code=404, detail="No conversation found")
    return messages

@router.post("/read", response_model=List[MessageResponse])
def mark_messages_as_read_endpoint(
    sender_id: int,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    POST /api/v1/messages/read

    현재 로그인한 사용자의, 특정 발신자(sender_id)로부터 온 메시지를 읽음 처리합니다.
    """
    updated_messages = message_service.mark_messages_as_read(db, receiver_id=current_user.id, sender_id=sender_id)
    return updated_messages