"""Warehouse transfers: stock moved between two warehouses at average cost.

Inside one branch the goods move at once and there is no entry (the inventory account is the same). Between two
branches they travel:

    send        (sending branch)    Dr Goods in Transit                 Cr Inventory
    receive     (sending branch)    Dr Inter-branch current account     Cr Goods in Transit
                (receiving branch)  Dr Inventory                        Cr Inter-branch current account

so the inter-branch accounts cancel on consolidation, and goods on the road stay on the sender's balance sheet until
they arrive. A different branch currency is converted at the rate of the day the goods were sent.
"""
from collections import defaultdict

from .db import q, x
from .i18n import t
from .ledger import AccountingError, audit, check_lock, company, create_move, cross_rate, now
from .money import translate
from .stock import EPS, _bump, _out_value, inventory_account, next_number, product, stock_journal, warehouse


def get(tid):
    return q("SELECT * FROM stock_transfers WHERE id = ?", (tid,), one=True)


def create(from_wid, to_wid, d, lines, notes=None, user_id=None):
    src, dst = warehouse(from_wid), warehouse(to_wid)
    if not src or not dst or src["id"] == dst["id"]:
        raise AccountingError(t("Choose two different warehouses."))
    lines = [ln for ln in lines if ln["quantity"] > EPS]
    if not lines:
        raise AccountingError(t("Nothing to move."))
    for ln in lines:
        if product(ln["product_id"])["type"] != "stock":
            raise AccountingError(t("Only stock products can be transferred."))
    tid = x("INSERT INTO stock_transfers (number, branch_id, from_warehouse_id, to_warehouse_id, to_branch_id, date, "
            "state, notes, created_by, created_at) VALUES (?,?,?,?,?,?, 'draft', ?, ?, ?)",
            (next_number("stock_transfers", "number", "WT", src["branch_id"], d), src["branch_id"], src["id"], dst["id"],
             dst["branch_id"], d, notes, user_id, now()))
    for ln in lines:
        x("INSERT INTO stock_transfer_lines (transfer_id, product_id, quantity) VALUES (?,?,?)",
          (tid, ln["product_id"], ln["quantity"]))
    return tid


def _picking(kind, tr, wid, branch_id, d, lines, signs, user_id):
    """A done picking recording the movement, so it shows in stock moves."""
    pid = x("INSERT INTO pickings (number, kind, branch_id, warehouse_id, date, state, notes, created_by, created_at) "
            "VALUES (?,?,?,?,?, 'done', ?, ?, ?)",
            (next_number("pickings", "number", "TRO" if kind == "transfer_out" else "TRI", branch_id, d), kind,
             branch_id, wid, d, tr["number"], user_id, now()))
    for ln, (dq, dv) in zip(lines, signs):
        x("INSERT INTO picking_lines (picking_id, product_id, quantity, unit_cost, qty_signed, value_signed) "
          "VALUES (?,?,?,?,?,?)", (pid, ln["product_id"], ln["quantity"],
                                   int(round(abs(dv) / ln["quantity"])) if ln["quantity"] else 0, dq, dv))
    return pid


def send(tid, d=None, user_id=None):
    tr = get(tid)
    if tr["state"] != "draft":
        raise AccountingError(t("This action is not allowed in the current state."))
    d = d or tr["date"]
    check_lock(d)
    lines = q("SELECT * FROM stock_transfer_lines WHERE transfer_id = ? ORDER BY id", (tid,))
    entry = defaultdict(int)
    signs = []
    for ln in lines:
        value = _out_value(ln["product_id"], tr["from_warehouse_id"], ln["quantity"])
        _bump(ln["product_id"], tr["from_warehouse_id"], -ln["quantity"], -value)
        x("UPDATE stock_transfer_lines SET value = ? WHERE id = ?", (value, ln["id"]))
        entry[inventory_account(product(ln["product_id"]))] -= value
        signs.append((-ln["quantity"], -value))
    out_pk = _picking("transfer_out", tr, tr["from_warehouse_id"], tr["branch_id"], d, lines, signs, user_id)
    from . import lots
    lots.record(out_pk)
    x("UPDATE stock_transfers SET out_picking_id = ?, sent_date = ? WHERE id = ?", (out_pk, d, tid))
    if tr["to_branch_id"] == tr["branch_id"]:
        _arrive(tid, d, user_id)
        return
    transit = company()["transit_account_id"]
    if not transit:
        raise AccountingError(t("Set the goods in transit account in Company settings."))
    entry[transit] += -sum(entry.values())
    move_id = _post(tr["branch_id"], d, entry, tr["number"], t("Goods sent to another branch"), user_id)
    src_cur = q("SELECT currency FROM branches WHERE id = ?", (tr["branch_id"],), one=True)["currency"]
    dst_cur = q("SELECT currency FROM branches WHERE id = ?", (tr["to_branch_id"],), one=True)["currency"]
    x("UPDATE stock_transfers SET state = 'in_transit', send_move_id = ?, rate = ? WHERE id = ?",
      (move_id, cross_rate(src_cur, dst_cur, d), tid))
    audit(user_id, "send", "stock_transfer", tid, tr["number"])


def _post(branch_id, d, entry, ref, narration, user_id):
    lines = [{"account_id": a, "label": ref, "debit": max(v, 0), "credit": max(-v, 0)} for a, v in entry.items() if v]
    if not lines:
        return None
    return create_move(branch_id, stock_journal(branch_id), d, lines, user_id=user_id, ref=ref, narration=narration,
                       move_type="stock", post=True)


def _arrive(tid, d, user_id):
    """Put the goods in the receiving warehouse (and, between branches, book both sides)."""
    tr = get(tid)
    lines = q("SELECT * FROM stock_transfer_lines WHERE transfer_id = ? ORDER BY id", (tid,))
    same = tr["to_branch_id"] == tr["branch_id"]
    signs, dest = [], defaultdict(int)
    total_dest = 0
    for ln in lines:
        vd = ln["value"] if same else translate(ln["value"], tr["rate"])
        _bump(ln["product_id"], tr["to_warehouse_id"], ln["quantity"], vd)
        x("UPDATE stock_transfer_lines SET value_dest = ? WHERE id = ?", (vd, ln["id"]))
        signs.append((ln["quantity"], vd))
        dest[inventory_account(product(ln["product_id"]))] += vd
        total_dest += vd
    in_pk = _picking("transfer_in", tr, tr["to_warehouse_id"], tr["to_branch_id"], d, lines, signs, user_id)
    from . import lots
    lots.record(in_pk, mirror=tr["out_picking_id"])
    vals = {"in_picking_id": in_pk, "received_date": d, "state": "done"}
    if not same:
        ic = q("SELECT id FROM accounts WHERE intercompany = 1 AND kind IN ('asset_current', 'liability_current') "
               "AND active = 1 ORDER BY code LIMIT 1", one=True)
        if not ic:
            raise AccountingError(t("Create an inter-branch account (flagged inter-branch) first."))
        sent = sum(ln["value"] for ln in lines)
        transit = company()["transit_account_id"]
        vals["receive_move_id"] = _post(tr["branch_id"], d, {ic["id"]: sent, transit: -sent}, tr["number"],
                                        t("Goods received by the other branch"), user_id)
        dest[ic["id"]] -= total_dest
        vals["dest_move_id"] = _post(tr["to_branch_id"], d, dest, tr["number"], t("Goods received from another branch"),
                                     user_id)
    x(f"UPDATE stock_transfers SET {', '.join(k + ' = ?' for k in vals)} WHERE id = ?", list(vals.values()) + [tid])
    audit(user_id, "receive", "stock_transfer", tid, tr["number"])


def receive(tid, d, user_id=None):
    tr = get(tid)
    if tr["state"] != "in_transit":
        raise AccountingError(t("This action is not allowed in the current state."))
    if d < tr["sent_date"]:
        raise AccountingError(t("Goods cannot arrive before they were sent."))
    check_lock(d)
    _arrive(tid, d, user_id)


def return_to_sender(tid, d, user_id=None):
    """Goods in transit that come back: into the sending warehouse again at the same cost."""
    tr = get(tid)
    if tr["state"] != "in_transit":
        raise AccountingError(t("This action is not allowed in the current state."))
    check_lock(d)
    lines = q("SELECT * FROM stock_transfer_lines WHERE transfer_id = ? ORDER BY id", (tid,))
    entry = defaultdict(int)
    for ln in lines:
        _bump(ln["product_id"], tr["from_warehouse_id"], ln["quantity"], ln["value"])
        entry[inventory_account(product(ln["product_id"]))] += ln["value"]
    entry[company()["transit_account_id"]] -= sum(ln["value"] for ln in lines)
    back = _picking("transfer_in", tr, tr["from_warehouse_id"], tr["branch_id"], d, lines,
                    [(ln["quantity"], ln["value"]) for ln in lines], user_id)
    from . import lots
    lots.record(back, mirror=tr["out_picking_id"])
    _post(tr["branch_id"], d, entry, tr["number"], t("Goods in transit returned"), user_id)
    x("UPDATE stock_transfers SET state = 'cancelled' WHERE id = ?", (tid,))
    audit(user_id, "cancel", "stock_transfer", tid, tr["number"])
