from django.db import models
from django.contrib.auth.models import User

class PushDevice(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="push_devices",
        help_text="User associated with this device (optional)."
    )
    device_token = models.CharField(
        max_length=255, 
        unique=True,
        help_text="The Expo push token for this device."
    )
    platform = models.CharField(
        max_length=50,
        choices=[
            ('ios', 'iOS'),
            ('android', 'Android'),
            ('web', 'Web'),
            ('unknown', 'Unknown')
        ],
        default='unknown'
    )
    device_id = models.CharField(
        max_length=255, 
        null=True, 
        blank=True,
        help_text="Unique device identifier (if available)."
    )
    app_version = models.CharField(
        max_length=50, 
        null=True, 
        blank=True
    )
    os_version = models.CharField(
        max_length=50, 
        null=True, 
        blank=True
    )
    is_active = models.BooleanField(
        default=True,
        help_text="Is this token still valid for push notifications?"
    )
    last_seen_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        username = self.user.username if self.user else "Anonymous"
        return f"{self.platform} Device ({username})"

    class Meta:
        ordering = ['-created_at']
        verbose_name = "Push Device"
        verbose_name_plural = "Push Devices"

class ContactQuery(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()
    subject = models.CharField(max_length=255)
    message = models.TextField()
    is_resolved = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.subject} - {self.email}"

    class Meta:
        ordering = ['-created_at']
        verbose_name = "Contact Query"
        verbose_name_plural = "Contact Queries"

class CategoryReference(models.Model):
    CATEGORY_CHOICES = [
        ('income', 'Income'),
        ('expense', 'Expense'),
        ('transfer', 'Transfer'),
    ]
    
    category_type = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
    phrase = models.CharField(max_length=255, help_text="The roman urdu or english phrase (e.g., 'paisy aaye')")
    vector = models.JSONField(null=True, blank=True, help_text="The pre-computed embedding vector")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.phrase} -> {self.category_type}"

class PushNotification(models.Model):
    title = models.CharField(max_length=255, help_text="Title of the push notification.")
    message = models.TextField(help_text="Body of the push notification.")
    media_file = models.FileField(
        upload_to='push_media/',
        blank=True, 
        null=True, 
        help_text="Optional. Upload an image or video to display in the notification."
    )
    action_link = models.CharField(
        max_length=255,
        blank=True, 
        null=True, 
        help_text="Optional. Call to action link (e.g. 'app://screen' or 'https://google.com')."
    )
    target_device = models.ForeignKey(
        PushDevice, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True,
        help_text="Select a specific device, or leave blank to send to ALL active devices."
    )
    extra_data = models.JSONField(
        null=True, 
        blank=True, 
        help_text="Optional JSON payload for additional custom data."
    )
    
    # Tracking
    success_count = models.IntegerField(default=0, editable=False)
    failure_count = models.IntegerField(default=0, editable=False)
    sent_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Push: {self.title} (Sent: {self.sent_at.strftime('%Y-%m-%d %H:%M')})"

    class Meta:
        ordering = ['-sent_at']
        verbose_name = "Broadcast Notification"
        verbose_name_plural = "Broadcast Notifications"
