# core/models_user.py
from django.conf import settings
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class UserPrefs(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="prefs")
    font_size = models.CharField(
        max_length=12,
        choices=[
            ("small", "Small"),
            ("default", "Default"),
            ("large", "Large"),
            ("xlarge", "Extra Large"),
        ],
        default="default",
    )

    def __str__(self):
        return f"UserPrefs({self.user_id}, font={self.font_size})"


class SearchHistory(models.Model):
    """
    Stores the last 10 searches per user. We de-duplicate only consecutive identical ones.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="search_history")
    q = models.CharField(max_length=1000, blank=True, default="")
    # Selected fields at time of search, e.g. {"subject": true, "application": false, ...}
    selected = models.JSONField(default=dict)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [models.Index(fields=["user", "-created_at"])]

    def __str__(self):
        return f"SearchHistory(u={self.user_id}, q={self.q!r})"


class ViewedIllustration(models.Model):
    """
    Logged after 10 seconds of visibility on an entry page. Keep 50 per user.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="recent_views")
    entry = models.ForeignKey("core.Entry", on_delete=models.CASCADE)
    viewed_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [models.Index(fields=["user", "-viewed_at"])]

    def __str__(self):
        return f"ViewedIllustration(u={self.user_id}, e={self.entry_id})"