from django.db import models
import uuid
from django.utils import timezone
from datetime import timedelta
from django.contrib.auth.hashers import make_password


# Create your models here.
class AppClients(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    application_name = models.CharField(max_length=255)
    application_type = models.CharField(max_length=255)
    contact_email = models.EmailField()
    contact_person_name = models.CharField(max_length=255)
    purpose = models.TextField()
    client_id = models.CharField(max_length=525, null=True, blank=True)
    client_secret = models.CharField(max_length=525, null=True, blank=True)
    approval_status = models.CharField(max_length=20, default="pending")

    def save(self, *args, **kwargs):
        self.contact_person_name = self.contact_person_name.title()
        self.approval_status = self.approval_status.upper()

        if self.client_secret:
            self.client_secret = make_password(self.client_secret)

        super(AppClients, self).save()

    def __str__(self):
        return f"{self.application_name} - {self.application_type}"


class IntegrationTokens(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    client = models.ForeignKey(
        AppClients,
        on_delete=models.CASCADE,
        related_name="client_tokens",
        null=True,
        blank=True,
    )
    access_token = models.CharField(max_length=525)
    refresh_token = models.CharField(max_length=525)
    access_token_expires_at = models.DateTimeField(null=True, blank=True)
    refresh_token_expires_at = models.DateTimeField(null=True, blank=True)

    @property
    def is_access_token_expired(self):
        if self.access_token_expires_at is None:
            return True

        expiration_time = timezone.localtime(self.access_token_expires_at)
        return timezone.localtime() > expiration_time

    @property
    def is_refresh_token_expired(self):
        if self.refresh_token_expires_at is None:
            return True

        expiration_time = timezone.localtime(self.refresh_token_expires_at)
        return timezone.localtime() > expiration_time
