"""Checkout, M-Pesa payment and order status."""
import logging
import secrets

import requests
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_POST
from pymongo import ReturnDocument

from . import mpesa
from .db import get_db, next_sequence
from .sms import notify_order_paid
from .utils import body, clean, err, normalise_phone, now, ok, to_int

log = logging.getLogger(__name__)
MAX_QTY = 20


def delivery_fee(method, subtotal):
    if method not in settings.DELIVERY:
        return None
    if method != "pickup" and subtotal >= settings.FREE_DELIVERY_OVER:
        return 0
    return settings.DELIVERY[method]


def public_order(o):
    o = clean(o)
    o.pop("access_key", None)
    pay = o.get("payment", {})
    o["payment"] = {k: pay.get(k) for k in ("method", "status", "receipt", "result_desc")}
    return o


@require_GET
def delivery_options(request):
    return ok({
        "options": [
            {"id": "pickup", "label": "Pick up from our shop (Nairobi CBD)", "fee": settings.DELIVERY["pickup"]},
            {"id": "nairobi", "label": "Delivery within Nairobi (same/next day)", "fee": settings.DELIVERY["nairobi"]},
            {"id": "countrywide", "label": "Countrywide courier (1–3 days)", "fee": settings.DELIVERY["countrywide"]},
        ],
        "free_over": settings.FREE_DELIVERY_OVER,
    })


@csrf_exempt
@require_POST
def create_order(request):
    """Body: {items:[{slug, qty}], customer:{name, phone, email?, location?, notes?}, delivery:"pickup|nairobi|countrywide"}

    Prices are always taken from the database, never from the client.
    """
    data = body(request)
    if not data:
        return err("Invalid JSON")
    items_in = data.get("items") or []
    if not isinstance(items_in, list) or not items_in or len(items_in) > 30:
        return err("Your cart is empty")

    c = data.get("customer") or {}
    name = (c.get("name") or "").strip()[:80]
    phone = normalise_phone(c.get("phone"))
    if len(name) < 2:
        return err("Please enter your name", field="name")
    if not phone:
        return err("Enter a valid Safaricom number, e.g. 0712 345 678", field="phone")
    method = data.get("delivery") or "pickup"
    if method != "pickup" and len((c.get("location") or "").strip()) < 3:
        return err("Please enter your delivery location", field="location")

    db = get_db()
    lines, subtotal = [], 0
    for it in items_in:
        slug = str(it.get("slug", ""))[:120]
        qty = to_int(it.get("qty"), 1, 1, MAX_QTY)
        p = db.products.find_one({"slug": slug, "active": True})
        if not p:
            return err("A product in your cart is no longer available. Please refresh your cart.")
        if p.get("stock", 0) < qty:
            return err(f"Only {p.get('stock', 0)} left of {p['name']}. Please update your cart.")
        line_total = int(p["price"]) * qty
        subtotal += line_total
        lines.append({
            "product_id": p["_id"], "slug": p["slug"], "name": p["name"],
            "price": int(p["price"]), "qty": qty, "total": line_total,
            "image": (p.get("images") or [None])[0],
        })

    fee = delivery_fee(method, subtotal)
    if fee is None:
        return err("Choose a delivery option")

    seq = next_sequence("order")
    order = {
        "order_no": f"BH{seq:05d}",
        "access_key": secrets.token_urlsafe(16),
        "items": lines,
        "subtotal": subtotal,
        "delivery_method": method,
        "delivery_fee": fee,
        "total": subtotal + fee,
        "customer": {
            "name": name, "phone": phone,
            "email": (c.get("email") or "").strip()[:120],
            "location": (c.get("location") or "").strip()[:200],
            "notes": (c.get("notes") or "").strip()[:500],
        },
        "status": "pending_payment",
        "payment": {"method": "mpesa", "status": "not_started"},
        "created_at": now(),
        "updated_at": now(),
    }
    res = db.orders.insert_one(order)
    order["_id"] = res.inserted_id
    return ok({"order": public_order(order), "access_key": order["access_key"]}, status=201)


def _get_order(order_no, key):
    if not key:
        return None
    return get_db().orders.find_one({"order_no": order_no, "access_key": key})


@csrf_exempt
@require_POST
def pay_order(request, order_no):
    """Trigger an M-Pesa STK push. Body: {key, phone?}"""
    data = body(request) or {}
    o = _get_order(order_no, data.get("key"))
    if not o:
        return err("Order not found", 404)
    if o["status"] != "pending_payment":
        return err("This order is already paid or closed")
    phone = normalise_phone(data.get("phone")) or o["customer"]["phone"]
    try:
        resp = mpesa.stk_push(phone, o["total"], o["order_no"], f"Order {o['order_no']}")
    except requests.RequestException:
        return err("Could not reach M-Pesa. Please try again in a moment.", 502)
    if str(resp.get("ResponseCode")) != "0":
        return err(resp.get("errorMessage") or resp.get("ResponseDescription") or "M-Pesa request failed", 502)

    get_db().orders.update_one({"_id": o["_id"]}, {"$set": {
        "payment.status": "awaiting_pin",
        "payment.phone": phone,
        "payment.checkout_request_id": resp["CheckoutRequestID"],
        "payment.merchant_request_id": resp.get("MerchantRequestID"),
        "payment.requested_at": now(),
        "updated_at": now(),
    }})

    if mpesa.is_mock():
        _mark_paid(resp["CheckoutRequestID"], {
            "result_code": 0, "result_desc": "Mock payment", "receipt": f"MOCK{secrets.token_hex(4).upper()}",
            "amount": o["total"], "phone": phone,
        })
    return ok({"message": resp.get("CustomerMessage", "Check your phone and enter your M-Pesa PIN")})


def _mark_paid(checkout_request_id, info):
    db = get_db()
    o = db.orders.find_one_and_update(
        {"payment.checkout_request_id": checkout_request_id, "status": "pending_payment"},
        {"$set": {
            "status": "paid",
            "payment.status": "paid",
            "payment.receipt": info.get("receipt"),
            "payment.amount": info.get("amount"),
            "payment.result_desc": info.get("result_desc"),
            "payment.paid_at": now(),
            "updated_at": now(),
        }},
        return_document=ReturnDocument.AFTER,
    )
    if o:
        for line in o["items"]:
            db.products.update_one({"_id": line["product_id"]},
                                   {"$inc": {"stock": -line["qty"], "sold": line["qty"]}})
        notify_order_paid(o)
    return o


def _mark_failed(checkout_request_id, info):
    get_db().orders.update_one(
        {"payment.checkout_request_id": checkout_request_id, "status": "pending_payment"},
        {"$set": {"payment.status": "failed", "payment.result_desc": info.get("result_desc"),
                  "payment.result_code": info.get("result_code"), "updated_at": now()}},
    )


@csrf_exempt
@require_POST
def mpesa_callback(request):
    key = settings.MPESA["CALLBACK_KEY"]
    if key and request.GET.get("k") != key:
        return err("forbidden", 403)
    data = body(request)
    info = mpesa.parse_callback(data)
    log.info("M-Pesa callback: %s", info)
    get_db().mpesa_callbacks.insert_one({"raw": data, "parsed": info, "received_at": now()})
    if info.get("checkout_request_id"):
        if str(info.get("result_code")) == "0":
            o = get_db().orders.find_one({"payment.checkout_request_id": info["checkout_request_id"]})
            if o and int(info.get("amount") or 0) < o["total"]:
                log.error("Underpayment on %s: %s < %s", o["order_no"], info.get("amount"), o["total"])
                _mark_failed(info["checkout_request_id"], {**info, "result_desc": "Amount mismatch"})
            else:
                _mark_paid(info["checkout_request_id"], info)
        else:
            _mark_failed(info["checkout_request_id"], info)
    # Daraja only needs an acknowledgement
    return ok({"ResultCode": 0, "ResultDesc": "Accepted"})


@require_GET
def order_status(request, order_no):
    """GET /api/orders/<no>?key=... — polled by the checkout page while waiting for the PIN."""
    o = _get_order(order_no, request.GET.get("key"))
    if not o:
        return err("Order not found", 404)
    pay = o.get("payment", {})
    # Fallback: if the callback hasn't arrived after ~40s, ask Daraja directly.
    if o["status"] == "pending_payment" and pay.get("status") == "awaiting_pin" and pay.get("requested_at"):
        requested = pay["requested_at"]
        if requested.tzinfo is None:
            from datetime import timezone
            requested = requested.replace(tzinfo=timezone.utc)
        if (now() - requested).total_seconds() > 40 and not pay.get("queried"):
            get_db().orders.update_one({"_id": o["_id"]}, {"$set": {"payment.queried": True}})
            try:
                q = mpesa.stk_query(pay["checkout_request_id"])
                code = str(q.get("ResultCode", ""))
                if code and code != "0":
                    _mark_failed(pay["checkout_request_id"], {"result_code": code, "result_desc": q.get("ResultDesc")})
            except requests.RequestException:
                pass
            o = get_db().orders.find_one({"_id": o["_id"]})
    return ok({"order": public_order(o)})
