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

from usuarios.models import Usuarios


# Create your models here.
class PlanSuscripciones(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50, null=False)
    description = models.CharField(max_length=50, null=False)
    price = models.IntegerField(null=False)
    interval = models.CharField(max_length=50, null=False)
    intervalCount = models.IntegerField(null=False)
    active = models.BooleanField(default=False)
    createdAt = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        # Busca el último ID manualmente
        if not self.id:
            max_id = PlanSuscripciones.objects.aggregate(models.Max('id'))['id__max'] or 0
            self.id = max_id + 1
        super().save(*args, **kwargs)

class Suscripciones(models.Model):
    id = AutoField(primary_key=True)
    userId = models.ForeignKey(Usuarios, on_delete=models.SET_NULL, null=True, blank=True)
    planId = models.ForeignKey(PlanSuscripciones, on_delete=models.SET_NULL, null=True, blank=True)
    status = models.CharField(max_length=30, null=False)
    startDate = models.DateTimeField(default=timezone.now)
    endDate = models.DateTimeField(default=timezone.now)
    nextBillingDate = models.DateTimeField(null=True, blank=True)
    canceledAt = models.DateTimeField(null=True, blank=True)
    createdAt = models.DateTimeField(auto_now_add=True)
    totalMeses = models.IntegerField(null=True, blank=True)
    mesesPagados = models.IntegerField(null=True, blank=True, default=0)

    def save(self, *args, **kwargs):
        # Busca el último ID manualmente
        if not self.id:
            max_id = Suscripciones.objects.aggregate(models.Max('id'))['id__max'] or 0
            self.id = max_id + 1
        super().save(*args, **kwargs)

class Pago(models.Model):
    id = models.AutoField(primary_key=True)
    suscriptionId = models.ForeignKey(Suscripciones, on_delete=models.SET_NULL, null=True, blank=True)
    monto = models.IntegerField(null=False)
    moneda = models.CharField(max_length=50, null=False)
    status = models.CharField(max_length=50, null=False)
    fechaPago = models.DateTimeField(null=True, blank=True)
    transactionId = models.CharField(max_length=100, null=False)
    notas = models.TextField(null=True, blank=True)
    createdAt = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        # Busca el último ID manualmente
        if not self.id:
            max_id = Pago.objects.aggregate(models.Max('id'))['id__max'] or 0
            self.id = max_id + 1
        super().save(*args, **kwargs)





