from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    ROLE_CHOICES = (
        ("landlord", "Landlord"),
        ("caretaker", "Caretaker"),
        ("tenant", "Tenant"),
    )

    phone_number = models.CharField(max_length=15, unique=True)
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, blank=True)
    is_first_login = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.username} ({self.role})"

    def save(self, *args, **kwargs):
        # Auto-assign landlord role for superusers
        if self.is_superuser:
            self.role = "landlord"

        # Enforce single landlord safely
        if self.role == "landlord":
            existing_landlord = User.objects.filter(role="landlord").exclude(pk=self.pk).first()
            if existing_landlord:
                raise ValueError("Only one landlord is allowed in the system.")

        super().save(*args, **kwargs)