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

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


class ETaxesVATOperations(Document):
	def on_trash(self):
		"""Защита от удаления если связано с Journal Entry"""
		if self.journal_entry:
			# Проверяем, существует ли Journal Entry
			if frappe.db.exists("Journal Entry", self.journal_entry):
				frappe.throw(
					_("Cannot delete or cancel E-Taxes VAT Operations {0} because it is linked with Journal Entry {1}").format(
						self.name,
						self.journal_entry
					)
				)

	def validate(self):
		"""Валидация при сохранении"""
		# Проверяем, что operation_id уникален
		if not self.is_new():
			return

		existing = frappe.db.get_value(
			'E-Taxes VAT Operations',
			{'operation_id': self.operation_id, 'name': ['!=', self.name]},
			'name'
		)

		if existing:
			throw(_("Operation ID {0} already exists in {1}").format(
				self.operation_id, existing
			))
