import uuid

from django.db import models

from apps.accounts.models import Company, TimeStampedModel, User


class InvoiceTemplate(TimeStampedModel):
    class Category(models.TextChoices):
        ACCOUNTING = 'accounting', 'Accounting'
        CORPORATE = 'corporate', 'Corporate'
        MODERN = 'modern', 'Modern'
        MINIMAL = 'minimal', 'Minimal'
        CREATIVE = 'creative', 'Creative'
        LEGAL = 'legal', 'Legal'
        MEDICAL = 'medical', 'Medical'
        CONSTRUCTION = 'construction', 'Construction'
        EDUCATION = 'education', 'Education'
        LUXURY = 'luxury', 'Luxury'
        GOVERNMENT = 'government', 'Government'
        CHURCH = 'church', 'Church'
        CONSULTING = 'consulting', 'Consulting'
        RESTAURANT = 'restaurant', 'Restaurant'
        SALON = 'salon', 'Salon'
        PHOTOGRAPHY = 'photography', 'Photography'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)
    category = models.CharField(max_length=32, choices=Category.choices)
    preview_image = models.ImageField(upload_to='template_previews/', blank=True, null=True)
    layout = models.JSONField(default=dict, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    usage_limit = models.PositiveIntegerField(null=True, blank=True)
    min_tier_required = models.CharField(max_length=32, default='free')
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.name


class PurchasedTemplate(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='purchased_templates')
    company = models.ForeignKey(
        Company, on_delete=models.CASCADE, related_name='purchased_templates', null=True, blank=True
    )
    template = models.ForeignKey(InvoiceTemplate, on_delete=models.PROTECT, related_name='purchases')
    uses_remaining = models.PositiveIntegerField(null=True, blank=True)
    purchased_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.user.email} - {self.template.name}'
