"""Customer credit control: credit limit, credit hold and overdue invoices, checked when a sale is committed.

Exposure = what the customer owes (receivable balance, all branches) + confirmed sales orders not yet invoiced
+ the document being confirmed, all in the company currency. The company policy decides whether going over the
limit only warns or stops the sale; a customer on credit hold is always stopped.
"""
from datetime import date

from flask import flash, has_request_context

from .db import q
from .i18n import nm, t
from .ledger import AccountingError, company, invoice_residuals, rate_on
from .money import fmt, translate


def _to_company(amount, currency, d):
    return translate(amount, rate_on(currency, d)) if amount else 0


def exposure(partner_id, d=None):
    """{balance, orders, total, overdue, oldest_days, overdue_n} in the company currency."""
    d = d or date.today().isoformat()
    bal = 0
    for r in q("SELECT b.currency, SUM(ml.debit - ml.credit) AS bal FROM move_lines ml JOIN moves m ON m.id = ml.move_id "
               "JOIN accounts a ON a.id = ml.account_id JOIN branches b ON b.id = ml.branch_id "
               "WHERE m.state = 'posted' AND a.kind = 'asset_receivable' AND ml.partner_id = ? GROUP BY b.currency",
               (partner_id,)):
        bal += _to_company(r["bal"], r["currency"], d)
    orders = 0
    from .stock import order_progress
    for o in q("SELECT o.id, b.currency FROM orders o JOIN branches b ON b.id = o.branch_id "
               "WHERE o.kind = 'sale' AND o.state = 'confirmed' AND o.partner_id = ?", (partner_id,)):
        prog = order_progress(o["id"])
        rest = 0
        for ln in q("SELECT * FROM order_lines WHERE order_id = ?", (o["id"],)):
            left = ln["quantity"] - prog[ln["id"]]["invoiced"]
            if left > 1e-9 and ln["quantity"]:
                rest += round((ln["subtotal"] + ln["tax_amount"]) * left / ln["quantity"])
        orders += _to_company(rest, o["currency"], d)
    invs = q("SELECT i.id, i.due_date, i.date, b.currency FROM invoices i JOIN branches b ON b.id = i.branch_id "
             "WHERE i.partner_id = ? AND i.kind = 'out_invoice' AND i.state = 'posted' AND COALESCE(i.due_date, i.date) < ?",
             (partner_id, d))
    res = invoice_residuals([i["id"] for i in invs], base=True)
    overdue, oldest, n = 0, 0, 0
    today = date.fromisoformat(d)
    for i in invs:
        r = res.get(i["id"], 0)
        if r > 0:
            overdue += _to_company(r, i["currency"], d)
            oldest = max(oldest, (today - date.fromisoformat(i["due_date"] or i["date"])).days)
            n += 1
    return {"balance": bal, "orders": orders, "total": bal + orders, "overdue": overdue, "oldest_days": oldest,
            "overdue_n": n}


def problems(partner, adding=0, d=None):
    """Reasons the customer is over its credit terms, given an extra amount (company currency) about to be added."""
    c = company()
    cur, dec = c["currency"], q("SELECT decimals FROM currencies WHERE code = ?", (c["currency"],), one=True)["decimals"]
    out = []
    if partner["credit_hold"]:
        out.append(t("the customer is on credit hold"))
    ex = None
    if partner["credit_limit"] or c["credit_overdue_days"]:
        ex = exposure(partner["id"], d)
    if partner["credit_limit"] and ex["total"] + adding > partner["credit_limit"]:
        out.append(f"{t('the credit limit of')} {cur} {fmt(partner['credit_limit'], dec)} {t('would be exceeded')} "
                   f"({t('exposure')} {cur} {fmt(ex['total'] + adding, dec)})")
    if c["credit_overdue_days"] and ex["oldest_days"] > c["credit_overdue_days"]:
        out.append(f"{t('an invoice is')} {ex['oldest_days']} {t('days overdue')} "
                   f"({t('limit')} {c['credit_overdue_days']})")
    return out


def issues(partner_id, amount, currency, d=None):
    """Problems a draft would run into when posted or confirmed (for a banner on the draft)."""
    d = d or date.today().isoformat()
    partner = q("SELECT * FROM partners WHERE id = ?", (partner_id,), one=True)
    if not partner or not (partner["credit_hold"] or partner["credit_limit"] or company()["credit_overdue_days"]):
        return []
    return problems(partner, _to_company(amount, currency, d), d)


def check(partner_id, amount, currency, d, what):
    """Called when a customer invoice is posted or a sales order confirmed. Stops it (hold, or policy 'block'),
    or lets it through with a warning (policy 'warn')."""
    partner = q("SELECT * FROM partners WHERE id = ?", (partner_id,), one=True)
    if not partner or not (partner["credit_hold"] or partner["credit_limit"] or company()["credit_overdue_days"]):
        return
    found = problems(partner, _to_company(amount, currency, d), d)
    if not found:
        return
    msg = f"{t('Credit control')} — {nm(partner)}: " + "; ".join(found) + "."
    if partner["credit_hold"] or company()["credit_policy"] == "block":
        raise AccountingError(msg + " " + t("Raise the credit limit or release the hold on the customer to continue.")
                              + f" ({t(what)})")
    if has_request_context():
        flash(msg, "error")
