from fastapi import Depends, APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from app.db import models
from app.core.security import get_current_user
from app.api import schemas
from fastapi.encoders import jsonable_encoder


# бд
def get_db():
    db = models.SessionLocal()
    try:
        yield db
    finally:
        db.close()


messagesRouter = APIRouter(
    prefix="/messages",
    tags=[],
)

@messagesRouter.get("/history/{contact_id}")
async def get_chat_history(
    contact_id: int, 
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db),
    limit: int = 50
):
    messages = db.query(models.Message).filter(
        (models.Message.sender_id == current_user.id) & (models.Message.receiver_id == contact_id) |
        (models.Message.sender_id == contact_id) & (models.Message.receiver_id == current_user.id)
    ).order_by(models.Message.timestamp.desc()).limit(limit).all()
    
    return jsonable_encoder(messages)


@messagesRouter.delete("/all")
async def delete_all_messages(
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    """Удалить все сообщения пользователя"""
    # Удаляем все сообщения, где пользователь либо отправитель, либо получатель
    db.query(models.Message).filter(
        (models.Message.sender_id == current_user.id) | (models.Message.receiver_id == current_user.id)
    ).delete()
    db.commit()
    
    return {"status": "ok", "detail": "Все сообщения удалены"}

