"""Build CRM quotation webhook payloads from ERP SalesQuotation records."""
from __future__ import annotations

from decimal import Decimal


def _d(value):
    return Decimal(str(value or "0").replace(",", "") or "0")


def quotation_has_price_change(quotation):
    if quotation.quotation_price_change_request_active:
        return True
    for item in quotation.sales_quotation_items.all():
        if item.request_price_change:
            return True
        if _d(item.discount_per_item) > 0 or _d(item.total_discount) > 0:
            return True
    return False


def build_crm_quotation_payload(quotation, event="created"):
    """Mirror CRM push-to-ERP item math for consistent totals."""
    customer = quotation.customer_profile
    staff = quotation.created_by
    items = []
    gross_total = Decimal("0")
    discount_total = Decimal("0")
    net_total = Decimal("0")

    for qi in quotation.sales_quotation_items.select_related("product").all():
        gross_total += _d(qi.gross_subtotal)
        discount_total += _d(qi.total_discount)
        net_total += _d(qi.net_subtotal)
        items.append({
            "erp_product_id": str(qi.product_id),
            "product_name": qi.product.product_name if qi.product else "",
            "quantity": int(float(qi.quantity or 0)),
            "price_per_item": float(_d(qi.price_per_item)),
            "discount_per_item": float(_d(qi.discount_per_item)),
            "gross_subtotal": float(_d(qi.gross_subtotal)),
            "total_discount": float(_d(qi.total_discount)),
            "net_subtotal": float(_d(qi.net_subtotal)),
            "request_price_change": bool(qi.request_price_change),
        })

    requires_approval = quotation_has_price_change(quotation)
    return {
        "event": event,
        "erp_quotation_id": str(quotation.id),
        "erp_quotation_number": quotation.sales_quotation_number,
        "crm_quote_uuid": quotation.crm_quote_uuid or "",
        "customer_email": (customer.email_address or "").strip().lower() if customer else "",
        "customer_first_name": customer.customer_first_name if customer else "",
        "customer_last_name": customer.customer_last_name if customer else "",
        "staff_id": str(staff.id) if staff else "",
        "quotation_net_value": str(quotation.quotation_net_value),
        "total_gross_value": str(gross_total.quantize(Decimal("0.01"))),
        "total_discount": str(discount_total.quantize(Decimal("0.01"))),
        "total_net_value": str(net_total.quantize(Decimal("0.01"))),
        "requires_price_approval": requires_approval,
        "sales_quotation_approved": bool(quotation.sales_quotation_approved),
        "created_in_erp": True,
        "items": items,
    }


def build_crm_quotation_converted_payload(quotation, order):
    payload = build_crm_quotation_payload(quotation, event="converted_to_order")
    payload["customer_order_number"] = order.customer_order_number
    payload["customer_order_id"] = str(order.id)
    return payload


def sync_quotation_to_crm(quotation, event="created", wait_on_create=False):
    from megawatt_api.crm_quote_webhook import notify_crm_quotation, apply_crm_quotation_response

    payload = build_crm_quotation_payload(quotation, event=event)
    response = notify_crm_quotation(payload, wait_for_response=(wait_on_create and event == "created"))
    if response:
        apply_crm_quotation_response(quotation, response)
    quotation.synced_to_crm = True
    quotation.save(update_fields=["synced_to_crm"])
    return payload
