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


class TelegramBot(models.Model):
    name = models.CharField(max_length=100, help_text="Произвольное имя бота в проекте")
    username = models.CharField(max_length=100, blank=True, help_text="@username в Telegram")
    token = models.CharField(max_length=200)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.name} ({self.username or 'no-username'})"


class BotConfig(models.Model):
    bot = models.OneToOneField(TelegramBot, on_delete=models.CASCADE, related_name="config")
    parse_mode = models.CharField(
        max_length=20, default="HTML",
        choices=[("HTML", "HTML"), ("MarkdownV2", "MarkdownV2"), ("None", "None")]
    )
    allowed_updates = models.JSONField(default=list, blank=True)
    admin_user_ids = models.JSONField(default=list, blank=True, help_text="Список Telegram user_id админов")
    webhook_url = models.URLField(blank=True, default="", help_text="Если используете вебхуки")
    use_webhook = models.BooleanField(default=False)

    def __str__(self):
        return f"Config for {self.bot}"


class TelegramChat(models.Model):
    """
    Храним все чаты, где бот состоит/состоял.
    chat_id в TG может быть до ~52 бит => BigInteger.
    """
    CHAT_TYPES = [
        ("private", "private"),
        ("group", "group"),
        ("supergroup", "supergroup"),
        ("channel", "channel"),
    ]

    id = models.BigIntegerField(primary_key=True)  # chat_id как PK
    type = models.CharField(max_length=20, choices=CHAT_TYPES)
    title = models.CharField(max_length=255, blank=True, default="")
    username = models.CharField(max_length=255, blank=True, default="")

    # Статус участия бота
    is_member = models.BooleanField(default=True)
    joined_at = models.DateTimeField(default=timezone.now)
    left_at = models.DateTimeField(null=True, blank=True)

    # Метаданные
    last_message_at = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        base = self.title or self.username or str(self.id)
        return f"{base} [{self.type}]"

    class Meta:
        verbose_name = "Telegram чат"
        verbose_name_plural = "Telegram чаты"
