from django.db import models
from tenant.models import TenantRoom
from utils.services import current_date

class Room(models.Model):
    hostel = models.ForeignKey('hostel.Hostel', on_delete=models.CASCADE, related_name='rooms')
    room_number = models.CharField(max_length=10)
    is_available = models.BooleanField(default=True) # type: ignore | for administrative purposes.
    room_type = models.CharField(
        max_length=20,
        choices=[('single', 'Single'), ('double', 'Double'), ('triple', 'Triple'), ('suite', 'Suite')],
        default='single',
    )
    total_beds = models.PositiveIntegerField(default=1) # type: ignore
    price_per_month = models.DecimalField(max_digits=10, decimal_places=2)
    last_electricity_reading = models.PositiveIntegerField(default=0)# type: ignore
    created_at = models.DateTimeField(auto_now_add=True, editable=True)
    updated_at = models.DateTimeField(auto_now=True, editable=True)


    def __str__(self):
        return f"{self.hostel.name} - Room {self.room_number}"

    @property
    def has_vacant_beds(self):  # or could be named 'has_space'
        occupancy = TenantRoom.objects.filter( # type: ignore
            room_id=self.pk,
            joined_on__lte=current_date(),
            left_on__isnull=True
        ).count()
        return occupancy < self.total_beds

    @property
    def is_bookable(self):
        """Room can be booked only if it's both administratively available and has vacant beds"""
        return self.is_available and self.has_vacant_beds

    class Meta:
        ordering = ['room_number']
        db_table = 'rooms' # custom table name
        unique_together = ('hostel', 'room_number')
