from flask import request, jsonify
from db_config import get_db_connection

def get_all_tasks():
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT * FROM tasks ORDER BY id DESC")
        tasks = cursor.fetchall()
        cursor.close()
        conn.close()
        return jsonify(tasks)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def delete_task():
    try:
        data = request.json
        task_id = data.get("id")
        if not task_id:
            return jsonify({"error": "Missing task ID"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM tasks WHERE id = %s", (task_id,))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": "Task deleted"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def create_task():
    try:
        data = request.json
        title = data.get("title")
        task_type = data.get("type")
        priority = data.get("priority")

        if not title or not task_type or not priority:
            return jsonify({"error": "Missing title, type, or priority"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("INSERT INTO tasks (title, type, priority) VALUES (%s, %s, %s)", (title, task_type, priority))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": "Task created"}), 201
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def update_task_field():
    try:
        data = request.json
        task_id = data.get("id")
        field = data.get("field")
        value = data.get("value")

        if not task_id or not field or value is None:
            return jsonify({"error": "Missing id, field, or value"}), 400

        if field not in ["title", "type", "priority"]:
            return jsonify({"error": "Invalid field"}), 400

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(f"UPDATE tasks SET {field} = %s WHERE id = %s", (value, task_id))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({"status": "Task updated"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
