# Copyright (c) 2025, JINGROW
# For license information, please see license.txt
from __future__ import annotations

import jingrow
from jingrow.model.page import Page


class PaymentDueExtension(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.types import DF

		amended_from: DF.Link | None
		extension_date: DF.Date
		reason: DF.SmallText
		team: DF.Link
	# end: auto-generated types

	def validate(self):
		if self.extension_date < jingrow.utils.today():
			jingrow.throw("Extension date cannot be in the past")

	def before_insert(self):
		if jingrow.db.exists(
			"Payment Due Extension",
			{"team": self.team, "pagestatus": 1, "extension_date": (">=", jingrow.utils.today())},
		):
			jingrow.throw("An active Payment due extension record already exists for this team")

	def on_submit(self):
		jingrow.db.set_value("Team", self.team, "extend_payment_due_suspension", 1)
	
	def on_cancel(self):
		jingrow.db.set_value("Team", self.team, "extend_payment_due_suspension", 0)


def remove_payment_due_extension():
	extensions = jingrow.get_all(
		"Payment Due Extension",
		{"pagestatus": 1, "extension_date": ("<", jingrow.utils.today())},
		pluck="team",
	)
	for team in extensions:
		jingrow.db.set_value("Team", team, "extend_payment_due_suspension", 0)
		jingrow.db.commit()
