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

import frappe
from frappe.model.document import Document


class BankIntegrationPurpose(Document):
	def autoname(self):
		# Name the record after the purpose text itself (like Kapital Bank Purpose),
		# truncated to 140 chars, with a -N suffix on collision.
		if not self.purpose_keyword:
			return

		name = str(self.purpose_keyword)
		if len(name) > 140:
			name = name[:137] + "..."

		original = name
		counter = 1
		while frappe.db.exists("Bank Integration Purpose", name):
			suffix = f"-{counter}"
			name = original[: 140 - len(suffix)] + suffix
			counter += 1

		self.name = name
