# plugins/ownership/routes.py

from datetime import datetime

from flask import Blueprint, request, jsonify, abort
from flask_login import login_required, current_user

from plugins.plant.models import db, Plant, PlantOwnershipLog
from plugins.auth.models import User   # Adjust import path if User lives elsewhere

bp = Blueprint("ownership", __name__, url_prefix="/ownership")


@bp.route("/transfer/<string:plant_uuid>", methods=["POST"])
@login_required
def transfer(plant_uuid):
    """
    Transfer a plant from the current owner to another user:
    Required JSON or form data: { "new_owner_id": <int> }
    """
    data = request.get_json() or request.form
    new_owner_id = data.get("new_owner_id", None)
    if not new_owner_id:
        return jsonify({"error": "new_owner_id is required"}), 400

    # 1) Fetch the plant by UUID
    plant = Plant.query.filter_by(uuid=plant_uuid).first()
    if not plant:
        return jsonify({"error": "Plant not found"}), 404

    # 2) Only current owner (or some admin) can transfer
    if plant.owner_id != current_user.id:
        return jsonify({"error": "Only the current owner can transfer this plant"}), 403

    # 3) Verify the new owner exists
    new_owner = User.query.get(new_owner_id)
    if not new_owner:
        return jsonify({"error": "New owner user not found"}), 404

    # 4) Create a log entry before changing owner
    log = PlantOwnershipLog(
        plant_id      = plant.id,
        user_id       = new_owner.id,
        date_acquired = datetime.utcnow(),
        transferred   = True,
        # If you want to store a reference to Neo4j node, set graph_node_id here. 
        graph_node_id = None,
        is_verified   = False
    )
    db.session.add(log)

    # 5) Update the Plant.owner_id
    plant.owner_id = new_owner.id
    db.session.add(plant)

    db.session.commit()

    return jsonify({
        "message": f"Plant '{plant.uuid}' transferred to user {new_owner.username}.",
        "plant_uuid": plant.uuid,
        "new_owner_id": new_owner.id
    }), 200
