"""
消息路由
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
from app.models import db, Message, Session

messages_bp = Blueprint('messages', __name__)


@messages_bp.route('/', methods=['POST'])
@jwt_required()
def send_message():
    """发送消息 (HTTP 方式)"""
    user_id = get_jwt_identity()
    data = request.get_json()
    
    session_id = data.get('session_id')
    content = data.get('content')
    message_type = data.get('type', 'text')
    reply_to = data.get('reply_to')
    
    if not all([session_id, content]):
        return jsonify({'error': 'Missing required fields'}), 400
    
    # 验证会话
    session = Session.query.filter_by(id=session_id, user_id=user_id).first()
    if not session:
        return jsonify({'error': 'Session not found'}), 404
    
    # 创建消息
    message = Message(
        session_id=session_id,
        sender_type='user',
        sender_id=user_id,
        message_type=message_type,
        content=content,
        reply_to=reply_to,
        status='sent',
        ack_status='pending'
    )
    
    db.session.add(message)
    
    # 更新会话
    session.message_count += 1
    session.last_active_at = datetime.utcnow()
    
    db.session.commit()
    
    return jsonify({'message': message.to_dict()}), 201


@messages_bp.route('/<message_id>', methods=['GET'])
@jwt_required()
def get_message(message_id):
    """获取单条消息"""
    message = Message.query.get(message_id)
    if not message:
        return jsonify({'error': 'Message not found'}), 404
    
    return jsonify({'message': message.to_dict()}), 200


@messages_bp.route('/<message_id>/ack', methods=['PUT'])
def acknowledge_message(message_id):
    """确认消息已送达"""
    message = Message.query.get(message_id)
    if not message:
        return jsonify({'error': 'Message not found'}), 404
    
    message.ack_status = 'acknowledged'
    message.delivered_at = datetime.utcnow()
    db.session.commit()
    
    return jsonify({'message': message.to_dict()}), 200


@messages_bp.route('/<message_id>/read', methods=['PUT'])
@jwt_required()
def mark_message_read(message_id):
    """标记消息已读"""
    message = Message.query.get(message_id)
    if not message:
        return jsonify({'error': 'Message not found'}), 404
    
    message.status = 'read'
    db.session.commit()
    
    return jsonify({'message': message.to_dict()}), 200
