
from django.db import models
from django.conf import settings


class StaffCheckIn(models.Model):

    STATUS_CHOICES = [
        ('on_time', 'On Time'),
        ('late', 'Late'),
    ]

    staff = models.ForeignKey(
        'NexusApp.Staff',
        on_delete=models.CASCADE,
        related_name='checkins'
    )

    check_in_date = models.DateField()

    check_in_time = models.DateTimeField()

    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='on_time'
    )

    late_reason = models.TextField(
        null=True,
        blank=True,
        help_text='Reason provided by staff for late check-in'
    )
    late_minutes = models.PositiveIntegerField(default=0)

    # where the staff member was (browser GPS) when checking in / out
    check_in_latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    check_in_longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    check_in_accuracy = models.PositiveIntegerField(null=True, blank=True, help_text='metres')
    check_in_location_note = models.CharField(max_length=120, blank=True, default='')

    check_out_time = models.DateTimeField(null=True, blank=True)
    check_out_latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    check_out_longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
    check_out_accuracy = models.PositiveIntegerField(null=True, blank=True, help_text='metres')
    check_out_location_note = models.CharField(max_length=120, blank=True, default='')

    working_minutes = models.PositiveIntegerField(null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'staff_checkins'
        ordering = ['-check_in_date', '-check_in_time']
        constraints = [
            models.UniqueConstraint(
                fields=['staff', 'check_in_date'],
                name='unique_staff_daily_checkin'
            )
        ]

    @property
    def working_hours_label(self):
        if self.working_minutes is None:
            return '-'
        return f'{self.working_minutes // 60}h {self.working_minutes % 60:02d}m'

    def __str__(self):
        return f'{self.staff} - {self.check_in_date} - {self.status}'
