"""Review routes (Trust System — Phase 2). Thin handlers only — all eligibility,
validation and persistence live in :mod:`app.reviews.services`."""

from __future__ import annotations

from flask import abort, flash, redirect, render_template, url_for
from flask_login import current_user, login_required

from app.reviews import reviews_bp
from app.reviews.forms import ReviewForm
from app.reviews.services import (
    ReviewError,
    get_transaction_or_404,
    has_reviewed,
    is_participant,
    submit_review,
)


@reviews_bp.route("/<public_id>", methods=["GET", "POST"])
@login_required
def submit(public_id: str):
    """Leave a review for the other party in a completed transaction."""
    transaction = get_transaction_or_404(public_id)
    # Non-participants must not even learn the transaction exists.
    if not is_participant(transaction, current_user):
        abort(404)

    listing = transaction.listing
    detail_url = url_for("marketplace.listing_detail", public_id=listing.public_id)
    if has_reviewed(transaction, current_user):
        flash("You have already reviewed this transaction.", "info")
        return redirect(detail_url)

    form = ReviewForm()
    if form.validate_on_submit():
        try:
            submit_review(transaction, current_user, form.rating.data, form.comment.data)
        except ReviewError as exc:
            flash(str(exc), "warning")
        else:
            flash("Review submitted. Thank you!", "success")
            return redirect(detail_url)

    reviewee = transaction.seller if current_user.id == transaction.buyer_id else transaction.buyer
    return render_template(
        "reviews/form.html", form=form, transaction=transaction, listing=listing, reviewee=reviewee
    )
