from django.db import models
from django.apps import apps
from django.utils import timezone

# Create your models here.

from .client import StripeClient
    
class StripeModel(models.Model):
    class STATUS_CHOICES(models.TextChoices):
        PENDING = "pending", "cz#Čeká se na platbu"
        PAID = "paid", "cz#Zaplaceno"
        FAILED = "failed", "cz#Neúspěšné"
        CANCELLED = "cancelled", "cz#Zrušeno"
        REFUNDING = "refunding", "cz#Platba se vrací"
        REFUNDED = "refunded", "cz#Platba úspěšně vrácena"
    
    status = models.CharField(max_length=20, choices=STATUS_CHOICES.choices, default=STATUS_CHOICES.PENDING)

    stripe_session_id = models.CharField(max_length=255, blank=True, null=True)
    stripe_payment_intent = models.CharField(max_length=255, blank=True, null=True)
    stripe_session_url = models.URLField(blank=True, null=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)

    def __str__(self):
        return f"Order {self.id} - {self.status}"
    
    
    
    def save(self, *args, **kwargs):
        # If new (no primary key yet)
        if self.pk is None:
            super().save(*args, **kwargs)  # Save first to get pk
            
            Order = apps.get_model('commerce', 'Order')
            Payment = apps.get_model('commerce', 'Payment')

            order = Order.objects.get(payment=Payment.objects.get(stripe=self))
            session = StripeClient.create_checkout_session(order)

            self.stripe_session_id = session.id
            self.stripe_payment_intent = session.payment_intent
            self.stripe_session_url = session.url
            
            # Save again with Stripe data
            super().save(update_fields=['stripe_session_id', 'stripe_payment_intent', 'stripe_session_url', 'updated_at'])
        else:
            self.updated_at = timezone.now()
            super().save(*args, **kwargs)

    def paid(self):
        self.status = self.STATUS_CHOICES.PAID
        self.save()

    def refund(self):
        StripeClient.refund_order(self.stripe_payment_intent)
        self.status = self.STATUS_CHOICES.REFUNDING
        self.save()

    def refund_confirmed(self):
        self.status = self.STATUS_CHOICES.REFUNDED
        self.save()

    def cancel(self):
        StripeClient.cancel_checkout_session(self.stripe_session_id)
        self.status = self.STATUS_CHOICES.CANCELLED
        self.save()