from django.core.exceptions import ValidationError
from django.db import models

class Address(models.Model):
    hostel = models.OneToOneField(
        'hostel.Hostel',
        on_delete=models.CASCADE,
        related_name="address_hostel",
        null=True, blank=True  # Optional for cases when it's a Tenant address
    )

    tenant = models.OneToOneField(
        'tenant.Tenant',
        on_delete=models.CASCADE,
        related_name="address_tenant",
        null=True, blank=True  # Optional for cases when it's a Hostel address
    )

    address_line = models.CharField(max_length=255)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    postal_code = models.CharField(max_length=20)
    country = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.address_line}, {self.city}, {self.state}, {self.country}"

    def clean(self):
        # Get all the ForeignKey fields in the model
        foreign_keys = [field for field in self._meta.fields if isinstance(field, models.ForeignKey)] # type: ignore

        # Check if at least one foreign key field is populated
        if not any(getattr(self, field.name) for field in foreign_keys):
            raise ValidationError("An address must be linked to at least one valid related model.")

    class Meta:
        ordering = ['city']
        db_table = 'addresses' # custom table name
