import uuid
from decimal import Decimal

from django.db import models


class Product(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True)
    description = models.TextField(blank=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.name


class Variant(models.Model):
    product = models.ForeignKey(Product, related_name="variants", on_delete=models.CASCADE)
    meta_product_id = models.CharField(max_length=200, unique=True, db_index=True)
    sku = models.CharField(max_length=100, unique=True)
    name = models.CharField(max_length=255)
    color = models.CharField(max_length=80, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    compare_at_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    stock_quantity = models.PositiveIntegerField(default=0)
    image_url = models.URLField(max_length=1000, blank=True)
    active = models.BooleanField(default=True)

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


class Coupon(models.Model):
    class DiscountType(models.TextChoices):
        PERCENT = "percent", "Percent"
        FIXED = "fixed", "Fixed amount"

    code = models.CharField(max_length=64, unique=True)
    discount_type = models.CharField(max_length=10, choices=DiscountType.choices)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    minimum_subtotal = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    active = models.BooleanField(default=True)
    starts_at = models.DateTimeField(null=True, blank=True)
    ends_at = models.DateTimeField(null=True, blank=True)
    max_uses = models.PositiveIntegerField(null=True, blank=True)
    use_count = models.PositiveIntegerField(default=0)

    def calculate_discount(self, subtotal):
        if self.discount_type == self.DiscountType.PERCENT:
            return (subtotal * self.amount / Decimal("100")).quantize(Decimal("0.01"))
        return min(self.amount, subtotal)

    def __str__(self):
        return self.code


class Order(models.Model):
    class Status(models.TextChoices):
        PENDING = "pending", "Pending payment"
        PAID = "paid", "Paid"
        CANCELLED = "cancelled", "Cancelled"
        FAILED = "failed", "Payment failed"

    public_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    authnet_invoice = models.CharField(max_length=20, unique=True, editable=False)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)
    email = models.EmailField()
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    address1 = models.CharField(max_length=255)
    address2 = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=120)
    state = models.CharField(max_length=80)
    postal_code = models.CharField(max_length=24)
    country = models.CharField(max_length=2, default="US")
    coupon_code = models.CharField(max_length=64, blank=True)
    subtotal = models.DecimalField(max_digits=10, decimal_places=2)
    discount = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    shipping = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    tax = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    total = models.DecimalField(max_digits=10, decimal_places=2)
    currency = models.CharField(max_length=3, default="USD")
    tracking = models.JSONField(default=dict, blank=True)
    authnet_transaction_id = models.CharField(max_length=64, blank=True)
    reservation_released = models.BooleanField(default=False)
    reservation_expires_at = models.DateTimeField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if not self.authnet_invoice:
            self.authnet_invoice = self.public_id.hex[:20].upper()
        super().save(*args, **kwargs)

    def __str__(self):
        return str(self.public_id)


class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE)
    variant = models.ForeignKey(Variant, on_delete=models.PROTECT)
    product_id_snapshot = models.CharField(max_length=200)
    sku = models.CharField(max_length=100)
    name = models.CharField(max_length=255)
    quantity = models.PositiveIntegerField()
    unit_price = models.DecimalField(max_digits=10, decimal_places=2)
    line_total = models.DecimalField(max_digits=10, decimal_places=2)


class PaymentEvent(models.Model):
    webhook_id = models.CharField(max_length=100, unique=True)
    event_type = models.CharField(max_length=120)
    transaction_id = models.CharField(max_length=64, blank=True)
    received_at = models.DateTimeField(auto_now_add=True)
