from flask import request, jsonify
from db_config import get_db_connection
from datetime import datetime, timedelta

def send_message():
    data = request.json
    sender_id = data.get("sender_id")
    receiver_id = data.get("receiver_id")
    content = data.get("content", "").strip()

    if not sender_id or not receiver_id or not content:
        return jsonify({"error": "Missing sender_id, receiver_id or content"}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        cursor.execute("""
            INSERT INTO messages (sender_id, receiver_id, content)
            VALUES (%s, %s, %s)
        """, (sender_id, receiver_id, content))

        conn.commit()
        cursor.close()
        conn.close()

        return jsonify({"message": "Message sent successfully"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def delete_message():
    message_id = request.json.get("message_id")
    if not message_id:
        return jsonify({"error": "Missing message_id"}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM messages WHERE id = %s", (message_id,))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"message": "Message deleted"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def get_conversation():
    user_id = request.args.get("user_id")
    friend_id = request.args.get("friend_id")

    if not user_id or not friend_id:
        return jsonify({"error": "Missing user_id or friend_id"}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)

        # Delete messages older than 30 days
        cursor.execute("""
            DELETE FROM messages
            WHERE (
               (sender_id = %s AND receiver_id = %s)
               OR (sender_id = %s AND receiver_id = %s)
              ) AND sent_at < (NOW() - INTERVAL 30 DAY)
        """, (user_id, friend_id, friend_id, user_id))

        # Fetch updated conversation
        cursor.execute("""
            SELECT * FROM messages
            WHERE (
               (sender_id = %s AND receiver_id = %s)
               OR (sender_id = %s AND receiver_id = %s))
            ORDER BY sent_at ASC
        """, (user_id, friend_id, friend_id, user_id))

        messages = cursor.fetchall()
        conn.commit()
        cursor.close()
        conn.close()

        return jsonify(messages)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
