from flask import request, jsonify
from db_config import get_db_connection

def send_notification():
    try:
        data = request.json
        user_id = data.get("user_id")
        title = data.get("title")
        message = data.get("message")

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

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO notifications (user_id, title, message, created_at)
            VALUES (%s, %s, %s, NOW())
        """, (user_id, title, message))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": "Notification sent"}), 201

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


def get_notifications_for_user(user_id):
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        cursor.execute("""
            SELECT id, title, message, created_at
            FROM notifications
            WHERE user_id = %s
            ORDER BY created_at DESC
        """, (user_id,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()
        return jsonify(results)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def delete_notification():
    try:
        data = request.json
        notif_id = data.get("notification_id")

        if not notif_id:
            return jsonify({"error": "Missing notification_id"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM notifications WHERE id = %s", (notif_id,))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": "Notification deleted"}), 200

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