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


class Notification(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="notifications",
    )
    title = models.CharField(max_length=255)
    message = models.TextField()
    type = models.CharField(max_length=50, default="info")
    is_read = models.BooleanField(default=False)
    metadata = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"{self.title} -> {self.user.email} (read: {self.is_read})"


class NotificationTemplate(models.Model):
    """Admin-configured message templates for notifying candidates about jobs.
    Placeholders: {{name}}, {{first_name}}, {{job_title}}, {{company}}, {{location}}."""

    class Channel(models.TextChoices):
        EMAIL = "EMAIL", "Email"
        WHATSAPP = "WHATSAPP", "WhatsApp"
        SMS = "SMS", "SMS"

    class Purpose(models.TextChoices):
        GENERAL = "GENERAL", "General / Job notification"
        OTP = "OTP", "OTP (verification code)"

    name = models.CharField(max_length=150)
    channel = models.CharField(max_length=10, choices=Channel.choices, default=Channel.EMAIL)
    # What the template is used for. The active OTP template per channel drives
    # OTP sends (SMS/WhatsApp) — nothing is hardcoded in settings.
    purpose = models.CharField(max_length=10, choices=Purpose.choices, default=Purpose.GENERAL)
    subject = models.CharField(max_length=255, blank=True, default="", help_text="Email subject (Email only).")
    body = models.TextField(help_text="Message body. Use {{name}}, {{job_title}}, {{company}}, {{location}}. For OTP use {{otp}}.")
    # For WhatsApp/SMS gateways that require a pre-approved template reference.
    # WhatsApp: approved template name. SMS: DLT content-id.
    provider_template_name = models.CharField(max_length=150, blank=True, default="")
    is_active = models.BooleanField(default=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL,
        related_name="notification_templates",
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "notification_templates"
        ordering = ["channel", "name"]

    def __str__(self):
        return f"[{self.channel}] {self.name}"
