from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


def user_profile_upload_path(instance, filename):
	# Files will be uploaded to MEDIA_ROOT/profile_pics/user_<id>/<filename>
	return f'profile_pics/user_{instance.user.id}/{filename}'


class Profile(models.Model):
	user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
	bio = models.TextField(blank=True, null=True)
	image = models.ImageField(upload_to=user_profile_upload_path, blank=True, null=True)
	is_seller = models.BooleanField(default=False)

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


@receiver(post_save, sender=User)
def ensure_profile_exists(sender, instance, created, **kwargs):
	if created:
		Profile.objects.create(user=instance)
	else:
		# save existing profile to ensure any related signals run
		try:
			instance.profile.save()
		except Exception:
			pass
