import factory
from django.utils.text import slugify
from django.contrib.auth import get_user_model
from faker import Faker

from account.models import Organization, Membership, UserProfile

User = get_user_model()
fake = Faker('nl_NL')

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User
        django_get_or_create = ('email',)

    email = factory.Faker('email', locale='nl_NL')
    password = factory.PostGenerationMethodCall('set_password', 'password123')

    @factory.post_generation
    def first_name(obj, create, extracted, **kwargs):
        if not create:
            return

        # De signal heeft het profiel al gemaakt, we passen het alleen aan
        profile, _ = UserProfile.objects.get_or_create(user=obj)
        profile.first_name = extracted or fake.first_name()
        profile.save()

    @factory.post_generation
    def last_name(obj, create, extracted, **kwargs):
        if not create:
            return

        profile, _ = UserProfile.objects.get_or_create(user=obj)
        profile.last_name = extracted or fake.last_name()
        profile.save()

class UserProfileFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = UserProfile
        # DIT IS DE FIX: Het voorkomt dat hij een nieuw profiel probeert te maken
        # als de signal er al een heeft aangemaakt voor deze user.
        django_get_or_create = ('user',)

    user = factory.SubFactory(UserFactory)
    first_name = factory.Faker('first_name', locale='nl_NL')
    last_name = factory.Faker('last_name', locale='nl_NL')


class OrganizationFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Organization

    name = factory.Faker('company', locale='nl_NL')
    slug = factory.LazyAttribute(lambda o: slugify(o.name))


class MembershipFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Membership

    user = factory.SubFactory(UserFactory)
    organization = factory.SubFactory(OrganizationFactory)
    role = 'owner'
