from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Dict

from app.core.database import get_db
from app.services.message_service import MessageService

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


@router.get("/daily", response_model=Dict)
async def get_daily_message(
    user_id: str,  # TODO: Pegar do JWT token quando implementar autenticação
    db: Session = Depends(get_db)
):
    """
    Retorna a mensagem motivacional do dia para o usuário.
    A mensagem é contextual baseada em:
    - Streaks e conquistas
    - Inatividade
    - Lembretes
    - Progresso
    - Hora do dia
    """
    try:
        message_service = MessageService(db)
        message = message_service.get_message_of_the_day(user_id)
        
        return {
            "success": True,
            "message": message
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/click/{message_id}")
async def mark_message_clicked(
    message_id: str,
    user_id: str,
    db: Session = Depends(get_db)
):
    """Marca mensagem como clicada pelo usuário"""
    from app.models.message import UserMessageLog
    from datetime import datetime
    
    try:
        log = db.query(UserMessageLog).filter(
            UserMessageLog.id == message_id,
            UserMessageLog.user_id == user_id
        ).first()
        
        if log:
            log.was_clicked = True
            log.clicked_at = datetime.now()
            db.commit()
            
            return {"success": True, "message": "Click registrado"}
        else:
            raise HTTPException(status_code=404, detail="Mensagem não encontrada")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/history")
async def get_message_history(
    user_id: str,
    limit: int = 10,
    db: Session = Depends(get_db)
):
    """Retorna histórico de mensagens do usuário"""
    from app.models.message import UserMessageLog
    
    try:
        logs = db.query(UserMessageLog).filter(
            UserMessageLog.user_id == user_id
        ).order_by(UserMessageLog.shown_at.desc()).limit(limit).all()
        
        return {
            "success": True,
            "messages": [
                {
                    "id": str(log.id),
                    "message_text": log.message_text,
                    "message_type": log.message_type,
                    "shown_at": log.shown_at.isoformat(),
                    "was_clicked": log.was_clicked
                }
                for log in logs
            ]
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
