from datetime import timedelta

from django.conf import settings
from django.db import models
from django.utils import timezone


class MembershipPlan(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    duration_days = models.PositiveIntegerField(default=30)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["price"]
        verbose_name = "абонемент"
        verbose_name_plural = "абонементы"

    def __str__(self) -> str:  # pragma: no cover - trivial
        return self.name


class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile"
    )
    phone = models.CharField(max_length=20, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "профиль"
        verbose_name_plural = "профили"

    def __str__(self) -> str:  # pragma: no cover - trivial
        return f"{self.user.username}"


class Subscription(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="subscriptions"
    )
    plan = models.ForeignKey(
        MembershipPlan, on_delete=models.PROTECT, related_name="subscriptions"
    )
    start_date = models.DateField(default=timezone.now)
    end_date = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-start_date"]
        verbose_name = "покупка абонемента"
        verbose_name_plural = "покупки абонементов"

    def __str__(self) -> str:  # pragma: no cover - trivial
        return f"{self.user} → {self.plan} ({self.start_date} — {self.end_date})"

    @property
    def is_active(self) -> bool:
        return self.end_date >= timezone.now().date()

    @classmethod
    def create_for_plan(cls, user, plan):
        """Helper to create subscription with calculated end date."""
        start_date = timezone.now().date()
        end_date = start_date + timedelta(days=plan.duration_days)
        return cls.objects.create(
            user=user, plan=plan, start_date=start_date, end_date=end_date
        )
