from django.db import models
from django.utils.timezone import now, timedelta
from accounts.models import Organization


def default_expiry():
    return now() + timedelta(minutes=5)


class Visitor(models.Model):
    org         = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='visitors')
    name        = models.CharField(max_length=150)
    dob         = models.CharField(max_length=20, blank=True)
    gender      = models.CharField(max_length=10, blank=True)
    address     = models.TextField(blank=True)
    # Any other org-chosen fields (mobile, email, pincode, careOf,
    # ageAbove18, residentImage, etc.) that aren't core columns above.
    extra_data  = models.JSONField(default=dict, blank=True)
    ip_address  = models.GenericIPAddressField(null=True, blank=True)
    user_agent  = models.TextField(blank=True)
    created_at  = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} — {self.org.name}"

    class Meta:
        ordering = ['-created_at']


class VisitorSession(models.Model):
    STATUS = [
        ('pending',    'Pending'),
        ('scanned',    'Scanned'),
        ('processing', 'Processing'),
        ('verified',   'Verified'),
        ('failed',     'Failed'),
        ('expired',    'Expired'),
        ('cancelled',  'Cancelled'),
    ]

    org        = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='sessions')
    session_id = models.CharField(max_length=100, unique=True)
    name       = models.CharField(max_length=150, blank=True)
    dob        = models.CharField(max_length=20, blank=True)
    extra_data = models.JSONField(default=dict, blank=True)
    status     = models.CharField(max_length=20, choices=STATUS, default='pending')
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    scanned_at = models.DateTimeField(null=True, blank=True)
    expires_at = models.DateTimeField(default=default_expiry)

    def is_expired(self):
        return now() > self.expires_at

    def __str__(self):
        return f"{self.session_id} — {self.status}"

    class Meta:
        ordering = ['-created_at']


class CallbackLog(models.Model):
    org        = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True, blank=True)
    endpoint   = models.CharField(max_length=200)
    method     = models.CharField(max_length=10)
    body       = models.TextField(blank=True)
    headers    = models.TextField(blank=True)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.endpoint} — {self.created_at}"

    class Meta:
        ordering = ['-created_at']
