from __future__ import annotations

from django.conf import settings
from django.db import models
from django.utils import timezone


class GoPayPayment(models.Model):
	# Optional user association
	user = models.ForeignKey(
		settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True, blank=True, related_name="gopay_payments"
	)

	# External identifiers and core attributes
	gopay_id = models.CharField(max_length=64, unique=True, db_index=True)
	order_number = models.CharField(max_length=128, blank=True, default="")
	amount = models.BigIntegerField(help_text="Amount in minor units (e.g., CZK in haléř).")
	currency = models.CharField(max_length=10)
	status = models.CharField(max_length=64, db_index=True, default="")
	preauthorized = models.BooleanField(default=False)
	captured_amount = models.BigIntegerField(default=0)

	# Raw payloads for traceability
	request_payload = models.JSONField(default=dict, blank=True)
	response_payload = models.JSONField(default=dict, blank=True)

	created_at = models.DateTimeField(default=timezone.now, db_index=True)
	updated_at = models.DateTimeField(auto_now=True)

	def __str__(self) -> str:
		return f"GoPayPayment(id={self.gopay_id}, status={self.status}, amount={self.amount} {self.currency})"


class GoPayRefund(models.Model):
	payment = models.ForeignKey(GoPayPayment, on_delete=models.CASCADE, null=True, blank=True, related_name="refunds")
	gopay_refund_id = models.CharField(max_length=64, blank=True, default="")
	
	amount = models.BigIntegerField(help_text="Amount in minor units.")
	status = models.CharField(max_length=64, blank=True, default="")
	payload = models.JSONField(default=dict, blank=True)

	created_at = models.DateTimeField(default=timezone.now, db_index=True)

	def __str__(self) -> str:
		return f"GoPayRefund(payment={self.payment_id}, amount={self.amount}, status={self.status})"


class GoPaySubscription(models.Model):
	parent_payment = models.ForeignKey(GoPayPayment, on_delete=models.CASCADE, related_name="subscriptions")
	recurrence_id = models.CharField(max_length=64, blank=True, default="")
	status = models.CharField(max_length=64, blank=True, default="")
	interval = models.CharField(max_length=64, blank=True, default="")
	next_payment_on = models.DateTimeField(null=True, blank=True)
	payload = models.JSONField(default=dict, blank=True)

	canceled = models.BooleanField(default=False)
	canceled_at = models.DateTimeField(null=True, blank=True)

	created_at = models.DateTimeField(default=timezone.now, db_index=True)

	def __str__(self) -> str:
		return f"GoPaySubscription(parent={self.parent_payment_id}, status={self.status})"
