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


class UserProfile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='userprofile',
    )
    bio = models.TextField(blank=True, default='')
    avatar = models.ImageField(
        upload_to='profiles/%d/',
        blank=True,
        null=True,
    )
    joined = models.DateTimeField(auto_now_add=True)

    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}...)'