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

BIO_MAX_LENGTH = 1000


class UserProfile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='userprofile',
    )
    bio = models.CharField(
        max_length=BIO_MAX_LENGTH,
        blank=True,
        default='',
    )
    avatar = models.OneToOneField(
        'library.FileIndex',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='profile',
    )
    joined = models.DateTimeField(auto_now_add=True)

    @property
    def avatar_url(self):
        if self.avatar_id is None:
            return None
        return reverse('library:file_request', args=[self.avatar.uuid])

    def __str__(self):
        return f'{self.user.username} profile'


class ApiToken(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='api_tokens',
    )
    token = models.TextField()
    key_prefix = models.CharField(max_length=8, db_index=True)
    label = models.CharField(max_length=64, default='API token')
    created_at = models.DateTimeField(auto_now_add=True)
    last_used = models.DateTimeField(null=True, blank=True)

    class Meta:
        indexes = [
            models.Index(fields=['user', 'key_prefix']),
        ]

    def __str__(self):
        return f'{self.user.username} - {self.label} ({self.key_prefix}...)'


class ImpersonationLog(models.Model):
    """Audit trail of staff impersonation sessions (reviewed in Django admin)."""
    impersonator = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='impersonation_sessions',
    )
    target = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='impersonated_sessions',
    )
    reason = models.CharField(max_length=255, blank=True, default='')
    started_at = models.DateTimeField(auto_now_add=True)
    ended_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-started_at']

    def __str__(self):
        return f'{self.impersonator.username} → {self.target.username}'