from django.contrib.auth.models import AbstractUser
from django.db import models
from django.core.exceptions import ValidationError
import re

def validate_friend_code(value):
    """Validate that friend code follows the format XXXX-XXXX-XXXX-XXXX where X is a digit."""
    if not re.match(r'^\d{4}-\d{4}-\d{4}-\d{4}$', value):
        raise ValidationError(
            'Friend code must be in format XXXX-XXXX-XXXX-XXXX where X is a digit.'
        )

class CustomUser(AbstractUser):
    default_friend_code = models.ForeignKey("FriendCode", on_delete=models.SET_NULL, null=True, blank=True)
    show_friend_code_on_link_previews = models.BooleanField(
        default=False,
        verbose_name="Show Friend Code on Link Previews",
        help_text="This will primarily affect share link previews on X, Discord, etc."
    )
    reputation_score = models.IntegerField(default=0)

    def __str__(self):
        return self.email

    def set_default_friend_code(self, friend_code):
        """Set a friend code as default if it belongs to the user."""
        if friend_code.user != self:
            raise ValidationError("Friend code does not belong to this user.")
        self.default_friend_code = friend_code
        self.save(update_fields=["default_friend_code"])

    def remove_default_friend_code(self, friend_code):
        """
        If the given friend code is the current default,
        assign another of the user's friend codes as default.
        Raises ValidationError if it's the only friend code.
        """
        if self.default_friend_code == friend_code:
            other_codes = self.friend_codes.exclude(pk=friend_code.pk)
            if not other_codes.exists():
                raise ValidationError("A user must always have a default friend code.")
            self.default_friend_code = other_codes.first()
            self.save(update_fields=["default_friend_code"])

class FriendCode(models.Model):
    friend_code = models.CharField(max_length=19, validators=[validate_friend_code])
    in_game_name = models.CharField(max_length=14, null=False, blank=False)
    user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, related_name='friend_codes')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        """
        When a new friend code is saved,
        if the user has no default friend code yet,
        automatically set this as the default.
        """
        is_new = self.pk is None
        super().save(*args, **kwargs)
        if is_new and not self.user.default_friend_code:
            self.user.default_friend_code = self
            self.user.save(update_fields=["default_friend_code"])

    def __str__(self):
        return self.friend_code