"""Verified-buyer reviews.

Only customers with a paid order containing the product can review it (order number + private order key).
Reviews are held for moderation; only approved reviews are shown and counted in AggregateRating schema,
so star ratings in Google always reflect real customers.
"""
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_POST, require_http_methods

from .auth import admin_required
from .db import get_db
from .utils import body, clean, err, now, ok, oid, to_int

PAID = ("paid", "processing", "dispatched", "completed")


def summary(slug, limit=10):
    db = get_db()
    approved = list(db.reviews.find({"product_slug": slug, "status": "approved"}).sort("created_at", -1))
    if not approved:
        return {"count": 0, "average": None, "items": []}
    avg = round(sum(r["rating"] for r in approved) / len(approved), 1)
    items = [{"name": r["name"], "rating": r["rating"], "title": r.get("title", ""), "body": r["body"],
              "date": r["created_at"], "verified": True} for r in approved[:limit]]
    return {"count": len(approved), "average": avg, "items": items}


@csrf_exempt
@require_POST
def submit(request):
    d = body(request) or {}
    db = get_db()
    order = db.orders.find_one({"order_no": d.get("order_no"), "access_key": d.get("key")})
    if not order or order["status"] not in PAID:
        return err("You can review products from a paid order only.", 403)
    slug = d.get("slug")
    if slug not in {i["slug"] for i in order["items"]}:
        return err("This product is not in your order.", 400)
    rating = to_int(d.get("rating"), 0, 0, 5)
    text = (d.get("body") or "").strip()
    if rating < 1:
        return err("Choose a rating from 1 to 5 stars.", field="rating")
    if len(text) < 15:
        return err("Please write at least a sentence about your experience.", field="body")
    if db.reviews.find_one({"order_no": order["order_no"], "product_slug": slug}):
        return err("You've already reviewed this product for this order. Thank you!", 409)
    name = (d.get("name") or order["customer"]["name"]).strip()[:40]
    db.reviews.insert_one({
        "product_slug": slug, "order_no": order["order_no"], "rating": rating,
        "title": (d.get("title") or "").strip()[:100], "body": text[:2000],
        "name": name.split(" ")[0] + (" " + name.split(" ")[1][0] + "." if len(name.split(" ")) > 1 else ""),
        "status": "pending", "created_at": now(),
    })
    return ok({"message": "Thanks! Your review will appear once it's approved."}, status=201)


@admin_required
@require_GET
def admin_list(request):
    status = request.GET.get("status", "pending")
    items = [clean(r) for r in get_db().reviews.find({"status": status}).sort("created_at", -1).limit(200)]
    return ok({"items": items})


@csrf_exempt
@admin_required
@require_http_methods(["PUT", "DELETE"])
def admin_item(request, rid):
    db = get_db()
    _id = oid(rid)
    if not _id or not db.reviews.find_one({"_id": _id}):
        return err("Not found", 404)
    if request.method == "DELETE":
        db.reviews.delete_one({"_id": _id})
        return ok({"deleted": True})
    status = (body(request) or {}).get("status")
    if status not in ("approved", "rejected", "pending"):
        return err("Invalid status")
    db.reviews.update_one({"_id": _id}, {"$set": {"status": status, "moderated_at": now(),
                                                  "moderated_by": request.admin["email"]}})
    return ok({"ok": True})
