"""
Provides routes for managing Settlement objects.
"""

from sqlalchemy.exc import SQLAlchemyError
from flask import jsonify, request

from piket_server.flask import app, db
from piket_server.models import Consumption, Settlement


@app.route("/settlements", methods=["GET"])
def get_settlements():
    """ Return a list of the active Settlements. """
    result = Settlement.query.all()
    return jsonify(settlements=[s.as_dict for s in result])


@app.route("/settlements/<int:settlement_id>", methods=["GET"])
def get_settlement(settlement_id: int):
    """ Show full details for a single Settlement. """
    s = Settlement.query.get_or_404(settlement_id)

    per_person = s.per_person

    return jsonify(settlement=s.as_dict, count_info=per_person)


@app.route("/settlements", methods=["POST"])
def add_settlement():
    """ Create a Settlement, and link all un-settled Consumptions to it. """
    json = request.get_json()

    if not json:
        return jsonify({"error": "Could not parse JSON."}), 400

    data = json.get("settlement") or {}
    s = Settlement(name=data["name"])

    db.session.add(s)
    db.session.commit()

    Consumption.query.filter_by(settlement=None).update(
        {"settlement_id": s.settlement_id}
    )

    db.session.commit()

    return jsonify(settlement=s.as_dict, count_info=s.per_person)