import frappe


def after_install():
    cleanup_payment_entry_custom_fields()
    ensure_bank_transaction_custom_fields()
    ensure_bank_account_custom_fields()
    ensure_payment_request_custom_fields()


def after_migrate():
    cleanup_payment_entry_custom_fields()
    ensure_bank_transaction_custom_fields()
    ensure_bank_account_custom_fields()
    ensure_payment_request_custom_fields()


KB_FIELDS = [
    "kb_section", "kb_transfer_type", "kb_operation_name", "kb_bank_id",
    "kb_transfer_status", "kb_column_break", "kb_from_iban", "kb_to_iban",
    "kb_to_tax_no", "kb_ben_bank_code",
]


def ensure_bank_transaction_custom_fields():
    if not frappe.db.exists("Custom Field", {"dt": "Bank Transaction", "fieldname": "kb_currency"}):
        cf = frappe.new_doc("Custom Field")
        cf.dt = "Bank Transaction"
        cf.fieldname = "kb_currency"
        cf.fieldtype = "Link"
        cf.options = "Currency"
        cf.label = "KB Currency"
        cf.insert_after = "currency"
        cf.read_only = 0
        cf.insert(ignore_permissions=True)
    frappe.db.commit()



def ensure_bank_account_custom_fields():
    existing = frappe.db.get_value(
        "Custom Field",
        {"dt": "Bank Account", "fieldname": "kb_bank_code"},
        ["name", "fieldtype"],
        as_dict=True,
    )
    if not existing:
        cf = frappe.new_doc("Custom Field")
        cf.dt = "Bank Account"
        cf.fieldname = "kb_bank_code"
        cf.fieldtype = "Link"
        cf.options = "Kapital Bank Bank Code"
        cf.label = "KB Bank Code"
        cf.insert_after = "bank_account_no"
        cf.read_only = 0
        cf.description = "Kapital Bank bank code required for outgoing transfers"
        cf.insert(ignore_permissions=True)
    elif existing.fieldtype != "Link":
        frappe.db.set_value(
            "Custom Field",
            existing.name,
            {"fieldtype": "Link", "options": "Kapital Bank Bank Code"},
        )
    frappe.db.commit()


def ensure_payment_request_custom_fields():
    # Clean up old field iterations
    for old in (
        "Payment Request-party_bank_account",
        "Payment Request-kb_company_bank_account",
    ):
        frappe.delete_doc("Custom Field", old, ignore_missing=True, force=True)

    _pr_fields = [
        {
            "fieldname": "kb_section",
            "fieldtype": "Section Break",
            "label": "Kapital Bank",
            "insert_after": "party_account_currency",
            "depends_on": "eval:doc.payment_request_type == 'Outward'",
        },
        {
            "fieldname": "kb_account",
            "fieldtype": "Link",
            "label": "Kapital Bank Account",
            "options": "Kapital Bank Account",
            "insert_after": "kb_section",
            "description": "Company KB account to send payment from. Must be mapped in Kapital Bank Settings.",
        },
        {
            "fieldname": "kb_column_break",
            "fieldtype": "Column Break",
            "insert_after": "kb_account",
        },
        {
            "fieldname": "kb_beneficiary_bank_account",
            "fieldtype": "Link",
            "label": "Beneficiary Bank Account",
            "options": "Bank Account",
            "insert_after": "kb_column_break",
            "description": "Supplier bank account with IBAN and KB Bank Code set.",
        },
    ]

    for f in _pr_fields:
        existing = frappe.db.get_value(
            "Custom Field", {"dt": "Payment Request", "fieldname": f["fieldname"]}, "name"
        )
        if existing:
            frappe.db.set_value("Custom Field", existing, {
                "label": f.get("label", ""),
                "insert_after": f["insert_after"],
                "depends_on": f.get("depends_on", ""),
                "mandatory_depends_on": "",
                "description": f.get("description", ""),
            })
        else:
            cf = frappe.new_doc("Custom Field")
            cf.dt = "Payment Request"
            cf.update(f)
            cf.read_only = 0
            cf.insert(ignore_permissions=True)

    frappe.db.commit()


def cleanup_payment_entry_custom_fields():
    for fieldname in KB_FIELDS:
        if frappe.db.exists("Custom Field", {"dt": "Payment Entry", "fieldname": fieldname}):
            frappe.delete_doc("Custom Field", f"Payment Entry-{fieldname}", ignore_missing=True)
    frappe.db.commit()
