"""Cheques received from customers and issued to vendors, including post-dated cheques (PDC).

Registering a cheque is a payment against the partner (and the invoice, if given), through the branch's cheque
journal instead of the bank:

    received   Dr Cheques Under Collection            Cr Receivable           (the invoice shows as paid)
    issued     Dr Payable                             Cr Post-dated Cheques Issued

On its date the cheque goes to the bank:

    received cleared    Dr Bank                       Cr Cheques Under Collection
    issued cleared      Dr Post-dated Cheques Issued  Cr Bank

A cheque that bounces (or is cancelled before it clears) takes the payment back: the invoice is open again and the
partner owes / is owed the amount as before.
"""
from datetime import date

from .db import placeholders, q, x
from .i18n import t
from .ledger import AccountingError, audit, check_lock, create_move, create_payment, now
from .stock import next_number

DIRECTIONS = {"received": {"label": "Cheques Received", "journal": "PDCR", "partner_type": "customer",
                           "payment_type": "inbound"},
              "issued": {"label": "Cheques Issued", "journal": "PDCP", "partner_type": "vendor",
                         "payment_type": "outbound"}}
STATES = {"registered": "In hand", "deposited": "Deposited", "cleared": "Cleared", "bounced": "Bounced",
          "cancelled": "Cancelled"}


def cheque_journal(branch_id, direction):
    j = q("SELECT * FROM journals WHERE branch_id = ? AND code = ? AND type = 'cheque'",
          (branch_id, DIRECTIONS[direction]["journal"]), one=True)
    if not j or not j["default_account_id"]:
        raise AccountingError(t("The branch has no cheque journal; check the cheque accounts in Company settings."))
    return j


def register(data, user_id=None):
    """data: direction, branch_id, partner_id, invoice_id, cheque_no, bank_name, issue_date, cheque_date, amount,
    bank_journal_id, notes. Books the payment and returns the cheque id."""
    direction = data["direction"]
    info = DIRECTIONS[direction]
    if data["amount"] <= 0:
        raise AccountingError(t("The amount must be greater than zero."))
    if not data.get("cheque_no"):
        raise AccountingError(t("Enter the cheque number."))
    no = data["cheque_no"].strip()
    if direction == "received":
        dup = q("SELECT number FROM cheques WHERE direction = 'received' AND partner_id = ? AND lower(trim(cheque_no)) = lower(?) "
                "AND lower(trim(COALESCE(bank_name, ''))) = lower(trim(?)) AND state NOT IN ('bounced', 'cancelled')",
                (data["partner_id"], no, data.get("bank_name") or ""), one=True)
    else:
        dup = q("SELECT number FROM cheques WHERE direction = 'issued' AND branch_id = ? AND lower(trim(cheque_no)) = lower(?) "
                "AND COALESCE(bank_journal_id, 0) = COALESCE(?, 0) AND state != 'cancelled'",
                (data["branch_id"], no, data.get("bank_journal_id")), one=True)
    if dup:
        raise AccountingError(t("Cheque number") + f" {no} " + t("is already registered") + f" ({dup['number']}).")
    if data["cheque_date"] < data["issue_date"]:
        raise AccountingError(t("The cheque date is before the date received / issued."))
    j = cheque_journal(data["branch_id"], direction)
    if data.get("invoice_id"):
        inv = q("SELECT currency FROM invoices WHERE id = ?", (data["invoice_id"],), one=True)
        if inv and inv["currency"]:
            raise AccountingError(t("Cheques are in the branch currency; this document is in") + f" {inv['currency']}.")
    pid = create_payment({"branch_id": data["branch_id"], "journal_id": j["id"], "partner_id": data["partner_id"],
                          "partner_type": info["partner_type"], "payment_type": info["payment_type"],
                          "date": data["issue_date"], "amount": data["amount"],
                          "ref": f"{t('Cheque')} {data['cheque_no']}", "invoice_id": data.get("invoice_id")}, user_id)
    prefix = "CHQR" if direction == "received" else "CHQI"
    cid = x("INSERT INTO cheques (number, direction, branch_id, partner_id, invoice_id, payment_id, cheque_no, bank_name, "
            "issue_date, cheque_date, amount, bank_journal_id, state, notes, created_by, created_at) "
            "VALUES (?,?,?,?,?,?,?,?,?,?,?,?, 'registered', ?, ?, ?)",
            (next_number("cheques", "number", prefix, data["branch_id"], data["issue_date"]), direction,
             data["branch_id"], data["partner_id"], data.get("invoice_id"), pid, data["cheque_no"],
             data.get("bank_name"), data["issue_date"], data["cheque_date"], data["amount"],
             data.get("bank_journal_id"), data.get("notes"), user_id, now()))
    audit(user_id, "register", "cheque", cid, data["cheque_no"])
    return cid


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


def deposit(cid, bank_journal_id, user_id=None):
    """A received cheque handed to the bank: no entry yet, it waits for the bank to clear it."""
    c = get(cid)
    if c["direction"] != "received" or c["state"] != "registered":
        raise AccountingError(t("This action is not allowed in the current state."))
    _bank(c, bank_journal_id)
    x("UPDATE cheques SET state = 'deposited', bank_journal_id = ?, deposit_date = ? WHERE id = ?",
      (bank_journal_id, date.today().isoformat(), cid))
    audit(user_id, "deposit", "cheque", cid, c["cheque_no"])


def _bank(c, bank_journal_id):
    j = q("SELECT * FROM journals WHERE id = ?", (bank_journal_id,), one=True)
    if not j or j["branch_id"] != c["branch_id"] or j["type"] != "bank" or not j["default_account_id"]:
        raise AccountingError(t("Choose a bank journal of the branch."))
    return j


def clear(cid, d, bank_journal_id=None, user_id=None):
    c = get(cid)
    if c["state"] not in ("registered", "deposited"):
        raise AccountingError(t("This action is not allowed in the current state."))
    if d < c["cheque_date"]:
        raise AccountingError(t("A cheque cannot clear before its date") + f" ({c['cheque_date']}).")
    bank = _bank(c, int(bank_journal_id or c["bank_journal_id"] or 0))
    pdc = cheque_journal(c["branch_id"], c["direction"])["default_account_id"]
    label = f"{t('Cheque')} {c['cheque_no']} {c['number']}"
    if c["direction"] == "received":
        lines = [{"account_id": bank["default_account_id"], "partner_id": c["partner_id"], "label": label,
                  "debit": c["amount"], "credit": 0},
                 {"account_id": pdc, "partner_id": c["partner_id"], "label": label, "debit": 0, "credit": c["amount"]}]
    else:
        lines = [{"account_id": pdc, "partner_id": c["partner_id"], "label": label, "debit": c["amount"], "credit": 0},
                 {"account_id": bank["default_account_id"], "partner_id": c["partner_id"], "label": label,
                  "debit": 0, "credit": c["amount"]}]
    move_id = create_move(c["branch_id"], bank["id"], d, lines, user_id, ref=c["number"],
                          narration=t("Cheque cleared"), partner_id=c["partner_id"], post=True)
    x("UPDATE cheques SET state = 'cleared', clear_date = ?, clear_move_id = ?, bank_journal_id = ? WHERE id = ?",
      (d, move_id, bank["id"], cid))
    audit(user_id, "clear", "cheque", cid, c["cheque_no"])
    return move_id


def bounce(cid, d, reason="", user_id=None, state="bounced"):
    """The cheque came back unpaid (or is cancelled): reverse the payment so the invoice is open again."""
    c = get(cid)
    if c["state"] not in ("registered", "deposited"):
        raise AccountingError(t("This action is not allowed in the current state."))
    p = q("SELECT * FROM payments WHERE id = ?", (c["payment_id"],), one=True)
    lines = [{"account_id": ln["account_id"], "partner_id": ln["partner_id"],
              "label": f"{t('Bounced cheque') if state == 'bounced' else t('Cancelled cheque')} {c['cheque_no']}",
              "debit": ln["credit"], "credit": ln["debit"]}
             for ln in q("SELECT * FROM move_lines WHERE move_id = ?", (p["move_id"],))]
    check_lock(d)
    move_id = create_move(c["branch_id"], p["journal_id"], d, lines, user_id, ref=c["number"],
                          narration=reason or (t("Bounced cheque") if state == "bounced" else t("Cancelled cheque")),
                          partner_id=c["partner_id"], post=True)
    # the payment no longer settles the invoice
    x("UPDATE payments SET state = 'cancelled' WHERE id = ?", (p["id"],))
    x("UPDATE cheques SET state = ?, bounce_date = ?, bounce_move_id = ?, bounce_reason = ? WHERE id = ?",
      (state, d, move_id, reason, cid))
    audit(user_id, state, "cheque", cid, c["cheque_no"])
    return move_id


def due(branch_ids, upto=None, direction=None):
    """Cheques not yet cleared whose date has come."""
    if not branch_ids:
        return []
    sql = (f"SELECT * FROM cheques WHERE state IN ('registered', 'deposited') AND cheque_date <= ? "
           f"AND branch_id IN ({placeholders(branch_ids)})")
    args = [upto or date.today().isoformat()] + list(branch_ids)
    if direction:
        sql += " AND direction = ?"
        args.append(direction)
    return q(sql + " ORDER BY cheque_date", args)
