import frappe
from frappe import _
from frappe.model.document import Document


class KapitalBankTransaction(Document):
	def on_trash(self):
		if self.payment_entry and frappe.db.exists("Payment Entry", self.payment_entry):
			frappe.throw(
				_("Cannot delete {0} because it is linked with Payment Entry {1}").format(
					self.name, self.payment_entry
				)
			)
		if self.bank_transaction and frappe.db.exists("Bank Transaction", self.bank_transaction):
			frappe.throw(
				_("Cannot delete {0} because it is linked with Bank Transaction {1}").format(
					self.name, self.bank_transaction
				)
			)

	def validate(self):
		if not self.is_new():
			return
		existing = frappe.db.get_value(
			"Kapital Bank Transaction",
			{"reference_no": self.reference_no, "name": ["!=", self.name]},
			"name",
		)
		if existing:
			frappe.throw(
				_("Reference No {0} already exists in {1}").format(self.reference_no, existing)
			)
