from __future__ import annotations

from django.db import models

from apps.core.models import TimeStampedModel


class PromotionPlan(TimeStampedModel):
    """Predefined promotion plan with pricing."""

    TYPE_CHOICES = [
        ("store", "Store Promotion"),
        ("product", "Product Promotion"),
    ]

    DURATION_CHOICES = [
        (6, "6 Months"),
        (12, "1 Year"),
        (36, "3 Years"),
    ]

    name_en = models.CharField("Plan Name (English)", max_length=100)
    name_ar = models.CharField("Plan Name (Arabic)", max_length=100, blank=True)
    type = models.CharField("Promotion Type", max_length=10, choices=TYPE_CHOICES)
    duration_months = models.PositiveSmallIntegerField(
        "Duration (Months)", choices=DURATION_CHOICES
    )
    price = models.DecimalField("Price (AED)", max_digits=10, decimal_places=2)
    is_active = models.BooleanField("Active", default=True)

    class Meta:
        db_table = "promotion_plans"
        ordering = ["type", "duration_months"]
        unique_together = ["type", "duration_months"]

    def __str__(self):
        return f"{self.name_en} — {self.duration_months}mo — {self.price} AED"


class Promotion(TimeStampedModel):
    """A promotion purchased by a store owner."""

    STATUS_CHOICES = [
        ("pending", "Pending Payment"),
        ("active", "Active"),
        ("expired", "Expired"),
        ("cancelled", "Cancelled"),
    ]

    owner = models.ForeignKey("users.User", on_delete=models.CASCADE, related_name="promotions")
    store = models.ForeignKey("stores.Store", on_delete=models.CASCADE, related_name="promotions")
    product = models.ForeignKey(
        "products.Product",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name="promotions",
    )
    plan = models.ForeignKey(PromotionPlan, on_delete=models.PROTECT, related_name="promotions")
    status = models.CharField("Status", max_length=10, choices=STATUS_CHOICES, default="pending")
    start_date = models.DateTimeField("Start Date", null=True, blank=True)
    end_date = models.DateTimeField("End Date", null=True, blank=True)
    amount_paid = models.DecimalField(
        "Amount Paid (AED)", max_digits=10, decimal_places=2, default=0
    )
    payment_reference = models.CharField("Payment Reference", max_length=200, blank=True)

    class Meta:
        db_table = "promotions"
        ordering = ["-created_at"]

    def __str__(self):
        target = self.product.name_en if self.product else self.store.name_en
        return f"{target} — {self.plan.name_en} ({self.status})"

    @property
    def is_store_promotion(self):
        return self.product is None

    @property
    def is_product_promotion(self):
        return self.product is not None
