"""Forms an owner uses on themselves."""
from django import forms
from django.contrib.auth import get_user_model

User = get_user_model()


class ProfileForm(forms.ModelForm):
    """Name and email address, edited by their owner.

    Username is deliberately not editable. Owners were migrated from WordPress
    with usernames they did not choose, and letting one be changed would strand
    the staff member who is reading it back to them over the phone. The email
    address is the identifier that matters, and it is editable.
    """

    class Meta:
        model = User
        fields = ["first_name", "last_name", "email"]
        labels = {
            "first_name": "First name",
            "last_name": "Last name",
            "email": "Email address",
        }
        help_texts = {
            "email": "Used to sign in, and where password reset links are sent.",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["email"].required = True

    def clean_email(self):
        """An address already in use would lock out both accounts.

        Sign-in accepts an email address, and the backend refuses to guess when
        two accounts share one — so a duplicate does not merely collide, it
        stops the other owner signing in too. Rejecting it here is the only
        place that is cheap to fix.
        """
        email = (self.cleaned_data.get("email") or "").strip()
        clash = User.objects.filter(email__iexact=email).exclude(pk=self.instance.pk)
        if email and clash.exists():
            raise forms.ValidationError(
                "Another account already uses that email address. "
                "If it is yours, ask the office to merge the two."
            )
        return email
