# endpoints/list_members.py
from flask import Blueprint, request, jsonify
from neo4j import GraphDatabase
from app import get_driver, neo4j_logger

bp = Blueprint('list_members', __name__)

@bp.route('/list_members', methods=['GET'])
@bp.route('/list_members', methods=['GET'])
def list_members():
    member_name = request.args.get('member_name')

    if not member_name:
        return jsonify({"error": "No member name provided"}), 400

    driver = get_driver()

    try:
        with driver.session() as session:
            result = session.run("""
                MATCH (m:Person {name: $memberName})-[*]-(n)
                WITH m, n, COLLECT(DISTINCT (m)-[r]->(n)) AS rels
                RETURN {
                    nodes: [
                        m,
                        n
                    ],
                    links: [
                        UNWIND rels AS rel
                        RETURN {
                            source: startNode(rel).id,
                            target: endNode(rel).id,
                            type: type(rel)
                        }
                    ]
                }
            """, memberName=member_name)

            record = result.single()

            if not record:
                return jsonify({"error": "No data found for the provided member name"}), 404

            # Extract nodes and links from the returned record
            nodes_data = []
            links_data = []

            nodes_record = record['nodes']
            links_record = record['links']

            # Process nodes
            for node in nodes_record:
                nodes_data.append({
                    "id": node.id,
                    "label": list(node.labels)[0] if node.labels else "",
                    "name": node.get("name", "")
                })

            # Process links
            for link in links_record:
                links_data.append({
                    "source": link['source'],
                    "target": link['target'],
                    "type": link['type']
                })

            data = {
                "nodes": nodes_data,
                "links": links_data
            }

            return jsonify(data)

    except Exception as e:
        neo4j_logger.error(f"Error querying Neo4j: {e}")
        return jsonify({"error": str(e)}), 500

@bp.route('/get_member_names', methods=['GET'])
def get_member_names():
    driver = get_driver()

    try:
        with driver.session() as session:
            result = session.run("MATCH (p:Person) RETURN p.name AS name")
            members = [record['name'] for record in result]
            return jsonify(members)

    except Exception as e:
        neo4j_logger.error(f"Error fetching member names: {e}")
        return jsonify({"error": str(e)}), 500
