# Copyright (c) 2026, JeyERP and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class BankStatementImporter(Document):
	def on_update(self):
		# Keep the registry records in sync with the mapping child tables:
		# removing a row OR clearing its erp_customer / erp_supplier flips the
		# corresponding registry record back to status=New.
		self._sync_customer_statuses()
		self._sync_supplier_statuses()

	def _sync_customer_statuses(self):
		mapped_names = {
			row.bi_customer_name
			for row in self.customer_mappings
			if row.bi_customer_name and row.erp_customer
		}
		orphaned = frappe.get_all(
			"Bank Integration Customer",
			filters={"status": "Mapped", "parent_bank_integration": self.name},
			fields=["name"],
		)
		for c in orphaned:
			if c.name not in mapped_names:
				frappe.db.set_value("Bank Integration Customer", c.name, {
					"status": "New",
					"mapped_customer": None,
					"customer_group": None,
					"territory": None,
					"payment_terms": None,
				}, update_modified=False)

	def _sync_supplier_statuses(self):
		mapped_names = {
			row.bi_supplier_name
			for row in self.supplier_mappings
			if row.bi_supplier_name and row.erp_supplier
		}
		orphaned = frappe.get_all(
			"Bank Integration Supplier",
			filters={"status": "Mapped", "parent_bank_integration": self.name},
			fields=["name"],
		)
		for s in orphaned:
			if s.name not in mapped_names:
				frappe.db.set_value("Bank Integration Supplier", s.name, {
					"status": "New",
					"mapped_supplier": None,
					"supplier_group": None,
					"payment_terms": None,
				}, update_modified=False)
