from django.db import models


class StoreComment(models.Model):
    """A comment left by a real visitor on a store coupon page.

    New comments are hidden until someone approves them in the Django admin.
    """

    store_slug = models.SlugField(max_length=255, db_index=True)
    name = models.CharField(max_length=60)
    email = models.EmailField(blank=True)  # never shown on the site
    body = models.TextField(max_length=1000)
    approved = models.BooleanField(default=False, db_index=True)
    reply = models.TextField(
        blank=True,
        help_text="Optional public reply, shown under the comment as 'SuperCosts Team'.",
    )
    ip_hash = models.CharField(max_length=64, blank=True, editable=False)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ["-created_at"]
        verbose_name = "store comment"
        verbose_name_plural = "store comments"

    def __str__(self):
        return f"{self.name} on {self.store_slug}"


class CouponVote(models.Model):
    """One 'Did this code work?' answer per visitor per coupon."""

    coupon_id = models.PositiveIntegerField(db_index=True)
    store_slug = models.SlugField(max_length=255, db_index=True)
    worked = models.BooleanField()
    voter_hash = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["coupon_id", "voter_hash"], name="one_vote_per_visitor_per_coupon"
            )
        ]
        verbose_name = "coupon vote"
        verbose_name_plural = "coupon votes"

    def __str__(self):
        return f"coupon {self.coupon_id}: {'worked' if self.worked else 'did not work'}"
